我有一张posts
表。我通过以下方式加入votes
表:
SELECT posts.*,
(CASE
WHEN vs.user_id = 1 THEN 0
ELSE 1
END) AS voted_by_me
FROM `posts`
LEFT OUTER JOIN votes AS vs ON vs.post_id = posts.id
GROUP BY posts.id
基本上我想知道连接值是否与user_id = 1.这显然不起作用,因为它只会在CASE WHEN条件中使用随机返回值。我想知道是否有办法找出连接值group by是否包含特定值。
澄清: 我想获取所有帖子,并且每个帖子都有一个名为voted_by_me的列,如果帖子由id为1的用户投票,则将其设为0,否则为1.
答案 0 :(得分:0)
这就是你想要的吗?
SELECT posts.id,
sum(vs.user_id = 1 AND vs.option = 0) > 0 AS downvoted_by_me,
sum(vs.user_id = 1 AND vs.option = 1) > 0 AS upvoted_by_me
FROM `posts`
LEFT OUTER JOIN votes AS vs ON vs.post_id = posts.id
GROUP BY posts.id
答案 1 :(得分:0)
SELECT posts.id,
ifnull(vs.isvoted, 0) AS voted_by_me
FROM `posts`
LEFT OUTER JOIN (select distinct postid , 1 as isvoted from votes where user_id=1) AS vs
ON vs.post_id = posts.id