2016-11-10 61 views
2

我試圖返回category.name的表格以及ED CHASE所在的電影的數量。即使ED CHASE未在該類別的電影中,查詢也應該返回每個類別。SQL - 電影ED CHASE的每個類別的計數已在

這是架構:

所有我到目前爲止是一種選擇所有類別名稱。儘管如此,我還是無法將其與ED CHASE聯繫起來。

SELECT category.name 
FROM film_category 
INNER JOIN category ON film_category.category_id = category.category_id, 

我試着加入這些結果與film_actor,但我一直試圖做的是,當越來越語法錯誤。

SELECT category.name 
FROM film_category 
INNER JOIN category ON film_category.category_id = category.category_id, 
INNER JOIN film_actor ON film_category.film_id = film_actor.film_id 

回答

2

試試這個:

SELECT c.category_id, c.name, COUNT(a.actor_id) 
FROM category AS c 
LEFT JOIN film_category AS fc ON c.category_id = fc.category_id 
LEFT JOIN film AS f ON fc.film_id = f.film_id 
LEFT JOIN film_actor AS fa ON f.film_id = fa.film_id 
LEFT JOIN actor AS a ON fa.actor_id = a.actor_id AND 
         a.first_name = 'ED' AND a.last_name = 'CHASE' 
GROUP BY c.category_id, c.name 

查詢將返回,即使這一類沒有與之相關的電影每一個類別的一個記錄。你可以改變這種情況,並使用INNER JOINfilm_category以防你只想要有至少有一個相關電影。