I have two tables in MySql i.e., subjects and photos and I wished to count the number of photos on each subjects
SELECT a.id, a.name, count(a.id) as `refcount`,
FROM `subjects` a
LEFT JOIN `photos` b ON (a.id = b.subject_id)
GROUP by a.id
ORDER BY a.name";
returns 1 even when the rowcount()=0. How to fix it
I tried various MySql syntax including count(field), but in vain
2
Answers
You will need to
count
photos.id (b.id), if no photos are found for the given subject, the query will return null, count(null) = 0.You can use this:
SELECT a.id, a.name, SUM(IF(b.id IS NULL, 0, 1)) as refcount, FROM subjects a LEFT JOIN photos b ON (a.id = b.subject_id) GROUP by a.id order by a.name
.PS: I didn’t try it