如何使用单个查询更新SQL而不是使用php循环?

时间:2013-05-22 10:38:46

标签: php mysql

这些是我的表格:

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  

我试过了:

UPDATE tbl_questions
JOIN (
SELECT id, COUNT(*) AS n 
FROM tbl_questions JOIN tbl_answers ON qid = tbl_questions.qid 
WHERE answercount = "0" 
GROUP BY id
) AS T USING (id)
SET num = n 
WHERE n > 0

我想更新那些得到的答案多于它的答案:
tbl_questions =>回答

如何更新比计算的问题多的行? (没有php循环)

1 个答案:

答案 0 :(得分:0)

UPDATE tbl_questions
  JOIN (
    SELECT tbl_questions.qid, COUNT(*) AS n 
    FROM tbl_questions JOIN tbl_answers ON tbl_answers.qid = tbl_questions.qid  
    GROUP BY qid
  ) AS T USING (qid)
SET answercount = n 
WHERE n > 0'