我有桌子'海报',表'评论'和表'预告片'。每个表都与一个movieID列相关联,但对于某些movieID,每个表都可以为空:
++ posters_table +++ ++ reviews_table ++ ++ trailers_table ++
--itemID--+--filename- --itemID--+--review-- --itemID--+--trailer
---------------------- --------------------- ---------------------
----001---+--0012343-- ----004---+--blalba-- ----002---+--002345--
----001---+--0013331-- ----004---+--xlalxa-- ----005---+--005434--
----002---+--0020052-- ----005---+--zlalza-- ----001---+--005335--
我想COUNT()指定movieID的海报,评论和预告片的数量,如果没有,则获得0。
所以,如果我想算上movieID = 001,我得到:['posters'] = 2 / ['reviews'] = 0和['trailers'] = 1(例如)
有人可以发布SQL查询来执行此操作吗?
答案 0 :(得分:3)
select
(select count(*) from posters_table where itemId = ?) as posters,
(select count(*) from reviews_table where itemId = ?) as reviews,
(select count(*) from trailers_table where itemId = ?) as trailers;
答案 1 :(得分:0)
我认为如果您将影片表格连接到给出计数的结果集,则可以选择计数是否为> 0并给出适当的值:
SELECT movieID, IF(posters.posters_count > 0, posters.posters_count,0) AS posters_total, IF(reviews.reviews_count > 0, reviews.reviews_count,0) AS reviews_total, IF(trailers.trailers_count > 0, trailers.trailers_count,0) AS trailers_total
FROM movies m
LEFT JOIN (SELECT itemID,COUNT(*) AS posters_count FROM posters_table WHERE itemID = '001' GROUP BY itemID) posters ON posters.itemID = movies.movieID
LEFT JOIN (SELECT itemID,COUNT(*) AS reviews_count FROM reviews_table WHERE itemID = '001' GROUP BY itemID) reviews ON reviews.itemID = movies.movieID
LEFT JOIN (SELECT itemID,COUNT(*) AS trailers_count FROM trailers_table WHERE itemID = '001' GROUP BY itemID) trailers ON trailers.itemID = movies.movieID
WHERE m.movieID = '001'
编辑:我更喜欢 ar 的解决方案。更简单!
答案 2 :(得分:0)
select
(select count(P.movieid) from posters P where P.movieid=1),
(select count(R.movieid) from reviews R where R.movieid=1),
(select count(T.movieid) from trailers T where T.movieid=1)
这些表并非“真正”加入,因此您需要三个选择。