I have the these tables:
- Users - id - Photos - id - user_id - Classifications - id - user_id - photo_id
I would like to order Users by the total number of Photos + Classifications which they own.
I wrote this query:
SELECT users.id, COUNT(photos.id) AS n_photo, COUNT(classifications.id) AS n_classifications, (COUNT(photos.id) + COUNT(classifications.id)) AS n_sum FROM users LEFT JOIN photos ON (photos.user_id = users.id) LEFT JOIN classifications ON (classifications.user_id = users.id) GROUP BY users.id ORDER BY (COUNT(photos.id) + COUNT(classifications.id)) DESC
The problem is that this query does not work as I expect and returns high numbers while I have only a few photos and classifications in the db. It returns something like this:
id n_photo n_classifications n_sum 29 19241 19241 38482 16 16905 16905 33810 1 431 0 431 ...