我有一个包含三个表格的数据库:USERS
PHOTOS
LIKES
,基本大纲如下:
USERS:
user_id
name
PHOTOS:
photo_id
title
url
user_id
LIKES:
user_id
photo_id
我想要做的是让用户喜欢很多照片并让很多用户喜欢这些照片。
显然,我想根据喜欢的数量订购这些照片,我可以使用JOIN
和COUNT()
我需要做的就是回复每张照片所拥有的“喜欢”的数量。我该怎么做?
我当前的SQL是:
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
答案 0 :(得分:2)
只需将COUNT(*)
添加到您的选择列表中:
SELECT
photos.photo_id,
photos.title,
photos.url,
users.name,
COUNT(*)
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
答案 1 :(得分:1)
试试这个,
SELECT
photos.photo_id,
photos.title,
photos.url,
users.name,
COUNT(*) AS COUNT
FROM photos, users
WHERE 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(likes.photo_id) DESC