2016-03-21 77 views
2

我寫了下面的查詢:顯示項目沒有價值

select title, branch_name, no_of_copies 
from Book_Copies BC 
inner join Book B on BC.book_id = B.book_id 
inner join Library_Branch LB on BC.branch_id = LB.branch_id 
where title = 'Grapes of Wrath'; 

但我的問題是,這種只顯示標題和具有> 0 no_of_copies分支名稱。如何顯示沒有no_of_copies行的行? (它將等於0)。

下面是表我目前得到:

+-----------------+-------------+--------------+ 
| title   | branch_name | no_of_copies | 
+-----------------+-------------+--------------+ 
| Grapes of Wrath | Central  |   5 | 
| Grapes of Wrath | Allentown |   2 | 
+-----------------+-------------+--------------+ 

這就是我需要的是:

+-----------------+-------------+--------------+ 
| title   | branch_name | no_of_copies | 
+-----------------+-------------+--------------+ 
| Grapes of Wrath | Central  |   5 | 
| Grapes of Wrath | Allentown |   2 | 
| Grapes of Wrath | Sharpstown |   0 | 
+-----------------+-------------+--------------+ 
+0

沒有看到表,我們無法修復您的查詢,但你需要使用一個左連接,而不是加盟都從左邊的表從右邊的項目和結果只有匹配 –

回答

3

您需要使用outer join而不是從book表開始。也許是這樣的:

select title, branch_name, no_of_copies 
from Book B 
    left join Book_Copies BC on BC.book_id = B.book_id 
    left join Library_Branch LB on BC.branch_id = LB.branch_id 
where title = 'Grapes of Wrath'; 

閱讀您的意見,這聽起來像你想使用library_branch一個cross join之間book得到的書籍和分支機構所有組合(或者稱爲cartesian product)。然後outer join這些結果與查找表:

select title, branch_name, coalesce(no_of_copies,0) copies 
from Book B 
    cross join Library_Branch LB 
    left join Book_Copies BC on BC.book_id = B.book_id 
          and BC.branch_id = LB.branch_id 
where title = 'Grapes of Wrath'; 
+0

我得到了相同的結果:/ – TheBandit

+0

@ TheBandit - 請發佈您的表格結構,樣本數據和預期結果。如果上面的查詢不能用'outer join',你確定你的'book'表有'title ='憤怒葡萄'的記錄嗎? – sgeddes

+0

是的,它確實有,我編輯我的問題與當前和預期的表 – TheBandit