【问题标题】:How to update SQL with single query and not with php loop? [duplicate]如何使用单个查询而不是 php 循环更新 SQL? [复制]
【发布时间】:2013-05-17 09:04:40
【问题描述】:

这些是我的桌子:

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循环)

【问题讨论】:

  • 如果你能告诉我为什么灵魂不工作不起作用,我会更有帮助。
  • 当您说它不起作用时,您的意思是查询不会运行,还是更新了不正确的行?
  • 查询不运行,不更新任何东西。
  • 您正在使用一个名为id 的字段,该字段在tbl_questions 表中不存在,您查询中的num 是什么?

标签: php mysql


【解决方案1】:
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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-26
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 2015-10-16
    • 2023-03-21
    • 2020-05-15
    相关资源
    最近更新 更多