我已经设置了一个竞赛视频提交的竞赛,然后人们对它们进行投票。提交内容将发送到具有以下结构的表submissions
中:
submission_id, title, videoname
投票表votes
结构是:
video_id, voter_id
video_id与提交表中的submission_id相关联。
我希望得到每个视频的投票数:
select video_id, count(1) from votes group by submission_id
但我也希望显示每个视频的标题,结果如下:
video_id, count, title
我是一个sql noob所以如果这是一个简单的陈述,请原谅我。我做了一些研究,并且无法自己想出一些东西,并希望得到任何帮助。
答案 0 :(得分:2)
我建议您使用LEFT JOIN
代替INNER JOIN
...而COUNT(v.video_id)
代替COUNT(*)
。这样您仍将返回当前有0票的提交:
select
s.submission_id as video_id,
count(v.video_id) as vote_count,
s.title
from
submissions s
left join votes v on v.video_id = s.submission_id
group by
s.submission_id,
s.title
答案 1 :(得分:0)
select s.submission_id, s.title, s.videoname, c.cnt
from
submissions s,
(select video_id, count(1) as cnt from votes group by video_id) c
where
s.submission_id = c.video_id
答案 2 :(得分:0)
这将返回您提交表中的每个视频,并在投票表中显示投票数。如果没有任何投票,它将显示在结果中,并使用NULL作为投票列
SELECT video_id, title, COUNT(voter_id) Votes
FROM submissions s
LEFT OUTER JOIN votes v ON s.submission_id = v.video_id
GROUP BY video_id, title,
答案 3 :(得分:0)
您必须进行联接以检索两个表之间的投票和视频标题,如下所示:
SELECT submissions.submission_id
, COUNT(1)
, submissions.videoname
FROM submissions LEFT OUTER JOIN votes
ON votes.video_id = submissions.submission_id
GROUP BY submissions.submission_id, submissions.videoname