Sql join查询并再选择一列

时间:2018-03-07 16:20:00

标签: mysql sql

我有三张牌桌:do scriptosascript -e 'tell app "Terminal" to do script "/usr/local/bin/python3.6 /path/to/testscript.py"' answers我已加入他们以获得我想要的结果

questions

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

如果用户提出了答案,即列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_answersuser_id(1或0 - 分别为upvote或downvote)

所以我的问题是: 我想再获得一个布尔结果的列,该列应该显示upvoted或downvoted,或者对于当前登录用户的每个答案没有任何内容

我尝试像这样编写查询

answer_id

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

1 个答案:

答案 0 :(得分:0)

考虑到给定用户只能对任何答案投票一次,这应该可以解决问题:

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,
       upvote_answers.upvote as upvote
FROM 
    answers
    JOIN questions on questions.id = answers.question_id
    JOIN users on users.id = answers.user_id
    LEFT JOIN upvote_answers ON
        upvote_answers.answer_id = answers.id AND
        upvote_answers.user_id = answers.user_id
WHERE 
    questions.question_active = 1 and 
    answers.answer_active = 1

如果LEFT JOIN子句匹配,则会生成结果,但如果不匹配,则会带来NULL个值(对于其表)。