我正在制作一个可以在图片上投票的应用程序。 我正在做一些连接,并想检查我得到的每张图片,如果登录的用户已投票。
我的投票表设置如下:
+-------------------------+
| id | user_id | photo_id |
+-------------------------+
| 1 | 2 | 6 |
+-------------------------+
| 2 | 4 | 5 |
+-------------------------+
| 3 | 3 | 5 |
+-------------------------+
| 4 | 1 | 6 |
+-------------------------+
我正在加入3个表:
用户,照片和投票
SELECT
users.*,
photos.*,
users.id as user_userid,
photos.id as photo_photoid,
COUNT(votes.id) as totalvotes
FROM
photos
LEFT JOIN
votes
ON
votes.photo_id = photos.id
LEFT JOIN
users
ON
users.id = photos.author_id
GROUP BY
photos.id
ORDER BY
totalvotes
DESC
我想在这个sql中做一个像这样的事情的查询:
+---------------------------------------------------------------------------------+
| photo_photoid | user_userid | totalVotes | currentUserHasVotetThisAmountOfTime |
+---------------------------------------------------------------------------------+
| 6 | 1 | 2 | 1 |
+---------------------------------------------------------------------------------+
| 5 | 1 | 2 | 0 |
+---------------------------------------------------------------------------------+
所以我想我正在寻找记录的计数,其中votes.user_id = $ MyLoggedInUser AND votes.photo_id = photo.id
有什么建议吗?
答案 0 :(得分:1)
以下是您的要求:
SELECT
v.photo_id,
COUNT(v.id) AS total_votes,
(SELECT COUNT(id) FROM vote WHERE photo_id = v.photo_id AND user_id = 1) AS currentUserHasVotetThisAmountOfTime
FROM
vote AS v
GROUP BY
v.photo_id
ORDER BY
total_votes
DESC
只需用您自己的ID替换user_id = 1
(在子请求行4中)。
我得到了user_id列,因为这是你提供的东西,所以在查询中也没有必要返回它。
如果您想自己测试一下:http://sqlfiddle.com/#!2/ba2a1/16/0