سؤال

I've two tables in MySQL: tracks and ratings. I want the query to count how much ratings there are per track, that's why I use the following:

SELECT t.*, COUNT(*) as ratings
FROM tracks t, ratings r
WHERE t.trackID = r.trackID
GROUP BY t.trackID
ORDER BY ratings DESC

Well my problem now is, that when a track doesn't have a rating yet (so count is 0) it won't show, but I also want it to show when there aren't any ratings yet. I hope someone can help me. Thanks in advance! Steven.

هل كانت مفيدة؟

المحلول

Try this, hope you'll find it helpful.

SELECT t.*, (select count(*) from ratings r where r.trackID = t.trackID) as ratingsCount from tracks t order by ratingsCount DESC; 

نصائح أخرى

You must use LEFT JOIN to preserve all left side (i.e. tracks) records.

SELECT t.*, COUNT(*) as ratings
FROM tracks t
  LEFT JOIN ratings r
ON t.trackID = r.trackID
GROUP BY t.trackID
ORDER BY ratings DESC
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top