I have a table like this:
// QandA
+----+----------------------------------------+---------+----------+-----------+
| Id | body
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