显示没有值的查询中的项目

时间:2016-03-21 18:08:15

标签: mysql

我写了以下查询:

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 |
+-----------------+-------------+--------------+

1 个答案:

答案 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';

阅读您的评论,听起来您希望在cross joinbook之间使用library_branch来获取图书和分支的所有组合(也称为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';