简体   繁体   中英

Displaying rows with count 0 in MySQL using COUNT and GROUP BY

I have two tables, Subject and Content, where Content references Subject with foreign key. I want to display how many times each subject appears in Content table (0, if it does not appear). But the query below only gives me the rows with count > 0 and ignores the others:

SELECT Subject.id, Subject.name, COUNT(Content.subject_id) AS `count`
FROM Subject LEFT JOIN Content
ON Subject.id = Content.subject_id
WHERE type = @type
GROUP BY Subject.id;

I checked and tried to follow this , this and this post but for some reason the code above does not work.

Any ideas?

Edit: the type field is in the Content table and that was causing the the problem as "Will A" pointed out

Which table is type a column in? I'm supposing that it's Content - and by including the field in the WHERE clause, you're forcing the Content table on the right-hand side of the LEFT JOIN to have data in it (which means the LEFT JOIN is actually then just an INNER JOIN).

Try:

SELECT Subject.id, Subject.name, COUNT(Content.subject_id) AS `count`
FROM Subject
LEFT JOIN Content
ON Subject.id = Content.subject_id
AND type = @type
GROUP BY Subject.id;

Which table does column type belong to? If type is in subject , your left join should work. So I assume that type is in Content . Then the problem is that your WHERE clause won't match the cases where there are no matching lines in Content . Use

WHERE (type = @type) OR (type IS NULL)

Do an outer join instead. Replace the null with a 0. Replace non null with a 1. Instead of count, do a sum of this column.

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM