2013-05-22 69 views
-1

這些都是我的表:如何使用單個查詢更新SQL,而不是使用php循環?

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 

我woud想更新那些已經得到更多的答案的問題比它就會計算:
tbl_questions => answercount

如何更新比計數更多的問題的行? (沒有PHP的循環)

+0

http://stackoverflow.com/questions/1262786/mysql-update-query-based-on-select-query – Cyclonecode

+0

這將幫助我更多,如果你能告訴我,爲什麼不soultion不工作。 – user2301881

+0

當你說它不工作時是否意味着查詢不會運行,或者不正確的行被更新? – Cyclonecode

回答

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'