有条件的INNER JOIN返回不需要的结果

时间:2012-04-16 13:58:35

标签: sql inner-join

基本上我使用LEFT JOIN表来获取属于PERSON的INVOICE记录。

快速浏览表格及相关记录。

table INVOICES    table GIGS        table BIDS               table PEOPLE
----------------  ----------------  -----------------------  ---------------- 
id | gig_id       id | bid_id       id | gig_id | person_id  id         
----------------  ----------------  -----------------------  ----------------
1  | 1            1  | 1             1 | 1      | 1          1
                  2  | 2             2 | 1      | 2          2

和我的加入查询...

SELECT invoices.* FROM invoices 
INNER JOIN gigs ON gigs.id = invoices.gig_id 
INNER JOIN bids ON bids.gig_id = gigs.id 
INNER JOIN people ON people.id = bids.person_id 
WHERE people.id = 2
GROUP BY invoices.id

和返回的结果......

INVOICE RESULT
--------------
id
--------------
1

事实是,people.id=2 没有有任何发票,但上述连接查询返回结果,就好像它们一样。当一个人没有任何发票时,我如何确保它返回空?

非常感谢有关此的任何提示!

1 个答案:

答案 0 :(得分:2)

使用LEFT OUTER JOIN代替INNER JOIN,并从People表(具有您想要查看全部数据的表)开始

这样的事情:

SELECT 
    People.Id,
    invoices.* 
FROM 
    People    
LEFT OUTER JOIN     -- this here *might* be an INNER JOIN
    bids ON people.person_id = bids.person_id 
LEFT OUTER JOIN     -- this here *might* be an INNER JOIN
    gigs ON bids.gig_id = gigs.id 
LEFT OUTER JOIN
    invoices  ON gigs.id = invoices.gig_id 
GROUP BY 
    invoices.id