在这种情况下我有
帖子表:
id
title
description
post_votes table:
id
post_id
user_id
评论表:
id
post_id
user_id
content
用户表:
id
username
我查询了我的索引页面(已登录的用户)
select
`posts`.`id`,
`posts`.`title`,
`posts`.`description`,
COUNT(distinct post_votes.id) AS votes,
COUNT(distinct comments.id) AS comments
from `posts`
left join `post_votes` on `post_votes`.`post_id` = `posts`.`id`
left join `comments` on `comments`.`post_id` = `posts`.`id`
group by `posts`.`id`
这显示所有帖子(事件)。每一个都显示总票数和评论数量。另外,在索引页面上显示每个帖子的投票按钮。
用户可以对文章进行投票,我希望能够检查用户是否已经对每个帖子进行了投票,并且在这种情况下显示已禁用此帖子的投票按钮。
我有用户ID。
我该怎么办?
答案 0 :(得分:1)
不确定mysql格式,但这样的事情应该有效:
select
CASE WHEN userVote.post_id IS NULL THEN 'No user vote' ELSE 'User has voted' END AS 'VoteStatus'
`posts`.`id`,
`posts`.`title`,
`posts`.`description`,
COUNT(distinct post_votes.id) AS votes,
COUNT(distinct comments.id) AS comments
from `posts`
left join `post_votes` on `post_votes`.`post_id` = `posts`.`id`
left join `post_votes` AS userVote on `post_votes`.`post_id` = `posts`.`id` AND `post_votes`.`user_id` = @myUserID
left join `comments` on `comments`.`post_id` = `posts`.`id`
group by `posts`.`id`