0

I have a posts table. I am joining it with votes table via:

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

Basically I want know if the joined value vs.user_id = 1. This obviously doesn't work because it will just use a random returned value in CASE WHEN condition . I am wondering if there's a way to find out if the join values group by contains a specific value.

To clarify: I want to get all posts, and also for each post have a column called voted_by_me where if posts was voted by user with id 1, then make it value 0, otherwise 1.

4

2 回答 2

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
于 2013-11-14T11:57:04.073 回答
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
于 2013-11-14T11:51:23.757 回答