简体   繁体   English

使用JOIN多对多表进行SQL查询

[英]SQL query with JOIN many-to-many table

I have three tables (simplified): 我有三个表(简化):

Item (Id, ItemName) 项目(ID,项目名称)

1 Item1
2 Item2
3 Item3

Supplier (Id, SupplierName) 供应商(编号,SupplierName)

1 Suppler1
2 Suppler2

SupplierM2MItem (ItemId, SupplierId) – foreign keys SupplierM2MItem(ItemId,SupplierId)–外键

1 1
1 2
2 1

I need to get all suppliers for all items like this: 我需要像这样的所有物品的所有供应商:

Item1 Supplier1
Item1 Supplier2
Item2 Supplier1
Item3

I believe it's not hard to achieve this but I can't. 我相信实现这一目标并不难,但我不能。 Can you please help 你能帮忙吗

The right solution uses outer joins: 正确的解决方案使用外部联接:

SELECT I.Item, S.Supplier
FROM Item I LEFT JOIN
     SupplierM2MItem S2I 
     ON I.Id = S2I.ItemID LEFT JOIN
     Supplier S
     ON S2I.SupplierID = S.ID;

I think it's an inner join plus an outer join. 我认为这是一个内部联接加上一个外部联接。 Try this: 尝试这个:

SELECT I.Item, S.Supplier
FROM Supplier S
LEFT OUTER JOIN
SupplierM2MItem S2I 
ON S2I.SupplierID = S.ID
INNER JOIN
Item I
ON I.Id = S2I.ItemID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM