我试图写一个查询,为所有的视频显示多少次,每一个已经被租用。即使它没有租过一次,计数也应该显示0。我知道我应该使用一个联盟来获得这些结果,但是试图让计数返回一个0是不成功的。
下面是我相当大的查询(它必须将多个表连接在一起):
select r.vid_id, movie_title, vid_format, count(r.client_num) "Num_Rental"
from rental r, client c, movie m, video v
where r.client_num = c.client_num
and r.vid_id = v.vid_id
and m.movie_num = v.movie_num
group by r.vid_id, movie_title, vid_format
union
select r.vid_id, movie_title, vid_format, count(*)
from rental r, client c, movie m, video v
where r.client_num = c.client_num
and r.vid_id = v.vid_id
and m.movie_num = v.movie_num
group by r.vid_id, movie_title, vid_format
order by movie_title, vid_format;但是,当我运行查询时,我得到:
VID_ID MOVIE_TITLE VID_FOR Num_Rental
------ ---------------------------------------- ------- ----------
120011 Gone with the Wind Blu-Ray 4
130012 Gone with the Wind DVD 3
220013 Indiana Jones and the Temple of Doom Blu-Ray 1
230012 Indiana Jones and the Temple of Doom DVD 1
210011 Indiana Jones and the Temple of Doom HD-DVD 2
130022 It's a Wonderful Life DVD 1
420011 One Flew Over the Cuckoo's Nest Blu-Ray 1
230033 Star Wars DVD 1
210031 Star Wars HD-DVD 2
210041 The Empire Strikes Back HD-DVD 1
130031 The Muppet Movie DVD 3
VID_ID MOVIE_TITLE VID_FOR Num_Rental
------ ---------------------------------------- ------- ----------
220062 The Phantom Menace Blu-Ray 1
330023 Toy Story DVD 1
320032 Toy Story 2 Blu-Ray 1
14 rows selected.在这个联盟中,对于许多视频,Num_rental的计数应该返回0,但我不知道该采取什么方法。如果有人能告诉我一些文档或类似的东西,我们将不胜感激。
发布于 2013-11-16 03:56:15
如果不确切地知道当前的模式,也不知道它的样本数据,就很难找到答案。但这应该会让你得到你想要的结果,或者至少指出正确的方向:
select r.vid_id, movie_title, vid_format, count(r.client_num) "Num_Rental"
from video v
left join rental r on r.vid_id = v.vid_id
left join movie m on m.movie_num = v.movie_num
left join client c on r.client_num = c.client_num
group by r.vid_id, movie_title, vid_format不管怎么说,我不知道你为什么要加入客户和电影才能计算录像的租金.似乎你可以直接加入租赁和视频。使其余的连接变得不必要。
https://stackoverflow.com/questions/20014432
复制相似问题