在SQL上过滤时包括0 On Count

时间:2015-05-06 01:53:08

标签: mysql sql

下面列出的是我的代码。它返回一个人参加电影的每个类别的计数。它返回结果,但我希望它列出每个类别,包括0计数的类别。我尝试了LEFT JOIN,OUTER JOIN等的每个组合,但它仍然无效。任何帮助将不胜感激!

SELECT c.name, COUNT(f.title) FROM category c
LEFT JOIN film_category fc ON c.category_id = fc.category_id
INNER JOIN film f ON fc.film_id = f.film_id
INNER JOIN film_actor fa ON f.film_id = fa.film_id
INNER JOIN actor a ON fa.actor_id = a.actor_id
WHERE a.first_name = 'Jack' AND a.last_name = 'Daniel'
GROUP BY c.name ASC;

2 个答案:

答案 0 :(得分:1)

试试这个。 SQL Fiddle demo

SELECT c.name, COUNT(f.title) FROM category c
LEFT JOIN film_category fc ON c.category_id = fc.category_id
LEFT JOIN film f ON fc.film_id = f.film_id
LEFT JOIN film_actor fa ON f.film_id = fa.film_id
LEFT JOIN actor a ON fa.actor_id = a.actor_id and a.first_name = 'Jack' AND a.last_name = 'Daniel'
WHERE 1=1 
GROUP BY c.name ASC;

答案 1 :(得分:-1)

结合查询的反向标准,例如

SELECT c.name, COUNT(f.ti....
...

UNION 

SELECT c.name, 0
FROM category c
...
WHERE NOT(a.first_name = 'Jack' AND a.last_name = 'Daniel')
...