2016-04-30 35 views
1

嗨,我被困在查詢我有一個這樣的表Mysql的加入選擇的記錄從表不是在其他表

budget_details

id budget_id expenditure_head_id budget 
1 1   1     1233 
2 1   2     333 
3 1   3     567 
4 2   1     343 
5 2   2     343 
6 2   3     6767 
7 2   4     557 

expenditure_heads

id name 
1 abc 
2 xyz 
3 qwe 
4 uvw 

我想從budget_details中獲得所有的支出,即使不支付 噸喜歡這裏budget_details budget_id = 1不包含expenditure_head_id 4 但我想選擇與0或空的顯示

我試過,但它沒有顯示expenditure_head_id 4

select `expenditure_heads`.`name`, `budget_details`.`budget`, `budget_details`.`id` from 
`budget_details` 
right join `expenditure_heads` on `budget_details`.`expenditure_head_id` = `expenditure_heads`.`id` 
where `budget_details`.`budget_id` = 1" 

請幫助

回答

1

where避免你得到你需要的缺失行。左連接在ON聲明上完成,因此此查詢應該適用於您:

SELECT EH.name, BD.budget, BD.id FROM expenditure_heads EH 
LEFT JOIN budget_details BD 
    ON (BD.expenditure_head_id = EH.id AND BD.budget_id = 1) 
+0

yes確切地說,避免丟失的行在哪裏。此查詢完美謝謝 – sanu

+0

如果答案解決了您的問題,請將其標記爲已回答。它可以幫助其他用戶。謝謝 – olibiaz

相關問題