How can I use JOIN in UPDATE statement?

前端 未结 1 1051
轻奢々
轻奢々 2020-12-22 04:28

I have a table like this:

// QandA
+----+----------------------------------------+---------+----------+-----------+
| Id |                   body                     


        
相关标签:
1条回答
  • 2020-12-22 05:09

    I think this should do it:

    UPDATE QandA AS ans1
    JOIN QandA AS ans2 ON ans2.related = ans1.related
    JOIN QandA AS ques ON ans2.related = ques.id
    SET ans1.accepted = (ans1.id = :answer_id)
    WHERE ques.author_id = :session_id
    AND ans2.id = :answer_id
    

    The first JOIN filters down to the answers to the same question as the answer being accepted.

    The second JOIN finds that question.

    The WHERE clause will restrict the update only to questions with the given author and specifies the answer ID being accepted.

    DEMO

    For the additional condition, add

    AND (ques.free IS NULL or ans1.accepted IS NULL)
    

    to the WHERE clause. ques.free IS NULL matches any free question, and ans1.accepted IS NULL matches a question with no accepted answer (because when an answer is accepted, all the other answers to that question get accepted = 0).

    DEMO of question with no accepted answer
    DEMO of question that's free

    0 讨论(0)
提交回复
热议问题