suppliers table:
PK_ID supplier supplier_code
1 x abc
2 y def
items table:
PK_ID item_name
1 Name1
2 Name2
items_suppliers table with FOREIGN KEYS:
FK_ID_items FK_ID_suppliers
1 1
2 1
I'd like to:
Select ONE item and find other items with the same suppliers from suppliers table.
It should return "Name2" item then.
[edited]:
Take ITEM1 and its all suppliers and find next item with every matched supplier ONLY THEN find next item with every supplier that matches.
PROPER ANSWER (CREDIT TO @DarwinvonCorax - with @ThorstenKettner invaluable help):
SELECT i2.item_name, s.supplier, s.supplier_code
FROM items i1
JOIN items_suppliers is1
ON i1.PK_ID = is1.FK_ID_items
JOIN items_suppliers is2
ON is1.FK_ID_suppliers = is2.FK_ID_suppliers
JOIN items i2
ON is2.FK_ID_items = i2.PK_ID
JOIN suppliers s
ON is1.FK_ID_suppliers = s.PK_ID
WHERE i1.item_name = 'Name1'
ORDER BY
CASE WHEN i2.item_name = 'Name1'
THEN 1
ELSE 2
END,
i2.item_name, s.supplier;
The solution proposed by @ThorstenKettner is also correct:
select item_name
from items
where pk_id in
(
select fk_id_items
from items_suppliers
where fk_id_suppliers in
(
select fk_id_suppliers
from items_suppliers
where fk_id_items =
(
select pk_id from items where item_name = 'Name1')
)
);
joinfor all tables. Andwherecomes afterjoinitem, not suprisingly ...