2012-04-16 66 views
1

基本上我使用LEFT JOIN表来获取属于PERSON的INVOICE记录。有条件的INNER JOIN返回非预期的结果

快速查看表格及相关记录。

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

恐怕你已经到简体这个问题不存在。您现在的查询无法运行,因为出价加入会引用出价没有的字段。团队也不应该在那里。 – HLGEM 2012-04-16 14:15:47

+0

@HLGEM,谢谢你对我错误的理解。我忘了在表格出价中加入“gig_id”列。 – chadwtaylor 2012-04-16 15:38:20

回答

2

使用LEFT OUTER JOIN而不是INNER JOINPeople表开始(在一个有你想看到所有的数据)

事情是这样的:

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