Question :
These are my tables:
tbl_answers =>
aid
qid
answer
uid
dateposted
emailnotify
namedisplay
status
isbestanswer
tbl_questions =>
qid
question
detail
mcid
cid
uid
answercount
dateposted
status
showname
emailnotify
question_type_id
I woud like to update those question that has got more answers than it’s counted in:
tbl_questions => answercount
How can I update the rows which have got more questions than it’s counted? (Without php loop)
This is how I’m trying now:
UPDATE tbl_questions
JOIN (
SELECT tbl_questions.qid, COUNT(*) AS n
FROM tbl_questions JOIN tbl_answers ON tbl_answers.qid = tbl_questions.qid
WHERE answercount = "0"
GROUP BY id
) AS T USING (tbl_answers.qid)
SET answercount = n
WHERE n > 0
IT says me You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.qid) SET answercount = n WHERE n > 0' at line 7
Answer :
Wouldn’t this be sufficient for your update, since the subquery providing the update value evaluates to 0 if there aren’t any answers for your question.
UPDATE tbl_questions q
SET q.answercount = (SELECT COUNT(*) FROM tbl_answers a WHERE a.qid = q.id)
WHERE q.answercount = 0