sql查询选择boolean

时间:2018-03-06 18:43:02

标签: mysql sql

我有三个表答案问题用户,我加入所有这些都得到了结果我正在

SELECT answers.answer_content as answer_content,
       answers.id as answer_id,
       answers.created_at as created_at,
       questions.id as question_id, 
       questions.question_title as question_title, 
       questions.question_slug as question_slug, 
       users.id as user_id, 
       users.name as user_name, 
       users.user_slug as user_slug,
                                  FROM answers
                                          JOIN questions
                                               on questions.id = answers.question_id
                                          JOIN users
                                               on users.id = answers.user_id
                                          WHERE questions.question_active = 1 and 
                                                answers.answer_active = 1

现在我还有一个名为upvote_answers的表。该表基本上存储upvote,downvote用于用户的答案。

如果用户赞成了答案,即列为user_id,answer_id,upvote(分别为1或0 - upvote或downvote)

所以我的问题是我希望得到一个布尔结果更多的coulmn,应该显示upvoted或downvoted或当前登录用户的每个答案没有

我试着写这样的

SELECT answers.answer_content as answer_content,
       answers.id as answer_id,
       answers.created_at as created_at,
       questions.id as question_id, 
       questions.question_title as question_title, 
       questions.question_slug as question_slug, 
       users.id as user_id, 
       users.name as user_name, 
       users.user_slug as user_slug,
       (SELECT count(upvote_answers.answer_id) from upvote_answers, answers WHERE upvote_answers.user_id = 2 and answers.id = upvote_answers.answer_id) as upvotedOrNot
                                  FROM answers
                                          JOIN questions
                                               on questions.id = answers.question_id
                                          JOIN users
                                               on users.id = answers.user_id
                                          WHERE questions.question_active = 1 and 
                                                answers.answer_active = 1

当用户登录时,他应该能够看到他是否已经投票或低估了答案。

0 个答案:

没有答案