我的数据库中有以下表格:
Films
(id,name)Awards
(id,name)Films_has_Awards
(film_id,awd_id)我怎样才能获得每部电影的奖项数量?
这是我的SQL查询:
SELECT
Films.name,
(SELECT COUNT(*)
FROM Films
JOIN Films_has_Awards ON Films_has_Awards.film_id = Films.id
JOIN Awards ON Awards.id = Films_has_Awards.awd_id) AS NumberOfAwards
FROM
Films;
但我每部电影的奖项总是相同。
答案 0 :(得分:2)
你的方法很好。在子查询中需要 correlation 条件:
Html.svg
注意:
SELECT f.name,
(SELECT COUNT(*)
FROM Films_has_Awards fha
WHERE fha.file_id = f.id
-----------------------------^ "correlates" to outer query
) AS NumberOfAwards
FROM Films f;
。答案 1 :(得分:0)
SELECT Films.name, Count(*)
FROM Films
JOIN Films_has_Awards
ON Films_has_Awards.film_id = Films.id
Group by Films.name
答案 2 :(得分:0)
display:block;