我写了以下查询:
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';
阅读您的评论,听起来您希望在cross join
和book
之间使用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';