SQL多个连接

时间:2015-02-04 16:21:24

标签: sql sql-server

我有4张桌子(如图所示),我想选择发票,发出发票的客户,以及发票的所有项目。

我无法弄清楚怎么样?我应该如何应用联接,还是应该使用子查询?

请帮助我,我真的很震惊。

Tables

先谢谢。

3 个答案:

答案 0 :(得分:2)

简单INNER JOIN应该有效

SELECT I.ItemID,
       C.ClientID,
       IV.InvoiceID
FROM   Items I
       INNER JOIN InvoiceItems II
               ON I.ItemID = II.ItemID
       INNER JOIN Invoice IV
               ON IV.InvoiceID = II.InvoiceID
       INNER JOIN Client C
               ON C.ClientID = IV.ClientID 

答案 1 :(得分:2)

Select c.ClientID, i.Invoiceid, it.itemId 
from Clients c
Inner Join Invoice i ON i.ClientId = c.ClientId
Inner Join InvoiceItems ii on ii.InvoiceId = i.InvoiceId
Inner Join Items it on ii.ItemId = it.ItemI
Order by c.Clientid, i.Invoiceid, it.itemId

可以根据需要添加其他列。

答案 2 :(得分:1)

问题是什么?这是一个简单的连接

Select * From InvoiceItems ii
Join Items i on ii.ItemID = i.ItemID
Join Invoice inv on ii.InvoceID = inv.InvoiceID
Join Clients c on inv.ClientID = c.ClientID