我有两张桌子,电影和预订。我试图弄清楚如何让我的查询只返回唯一的电影ID /标题,并将每个电影中多个条目的表中列出的票证总数相加。 以下是我尝试的,没有运气。我在这里缺少什么?
SELECT movies.id AS id, movies.title AS title, SUM(reservations.number_of_tickets) AS sold_tickets
FROM reservations
INNER JOIN movies ON reservations.movie_id = movies.id
ORDER BY sold_tickets DESC, id
当我在不尝试SUM的情况下运行查询时,我几乎得到了我想要的内容,除了查询对同一部电影有多行:
SELECT movies.id AS id, movies.title AS title, reservations.number_of_tickets AS sold_tickets
FROM reservations
INNER JOIN movies ON reservations.movie_id = movies.id
ORDER BY sold_tickets DESC, id
感谢您的帮助!
答案 0 :(得分:1)
您错过了GROUP BY
:
SELECT m.id, m.title, SUM(r.number_of_tickets) AS sold_tickets
FROM movies m INNER JOIN
reservations r
ON r.movie_id = m.id
GROUP BY m.id, m.title
ORDER BY sold_tickets DESC, id;
注意:
movies.id
已在结果集中调用id
。join
s的顺序。如果您想要无预约的电影,我可以将INNER JOIN
变为LEFT JOIN
。