I have a database of three tables: USERS PHOTOS LIKES and a basic outline would be like so:
USERS:
user_id
name
PHOTOS:
photo_id
title
url
user_id
LIKES:
user_id
photo_id
What I want to do is enable a user to like many photos and have photos liked by many users.
Obviously, I want to order these photos by the number of likes, which I can do with a JOIN and COUNT()
What I need to do which I can’t figure out is return the number of ‘likes’ which each photo has. How would I do this?
my current SQL is:
SELECT
photos.photo_id,
photos.title,
photos.url,
users.name
FROM photos
LEFT OUTER JOIN users
ON users.user_id = photos.user_id
LEFT OUTER JOIN likes
ON likes.photo_id = photos.photo_id
GROUP BY likes.photo_id
ORDER BY COUNT(*) DESC
LIMIT 20
Just add
COUNT(*)to your select list: