更新记录错误:无效使用组功能更新以å‰çš„所有数æ®

时间:2018-06-19 20:37:32

标签: php mysql

$sql = "UPDATE purchase SET stat='1' WHERE `id`='$id' AND 4*(plan)<= sum(plan) ";

或

$sql = "UPDATE purchase SET stat='1' WHERE `id`='$id' AND 4*(plan-1)<= sum(plan-1) ";

我正在å°è¯•é€šè¿‡æ­¤æ›´æ–°è¿›è¡ŒæŸ¥è¯¢ï¼Œå¦‚果所有行的总和大于第一行,它将更新第一行,并且此规则适用于所有行。但是它显示错误并说

Error updating record: Invalid use of group function 

此查询有什么问题?我需è¦æ­¤é”™è¯¯çš„帮助。

1 个答案:

答案 0 :(得分:1)

您ä¸èƒ½åœ¨æŸ¥è¯¢çš„SUM()å­å¥ä¸­ä½¿ç”¨åƒWHERE这样的èšåˆå‡½æ•°ï¼Œå› ä¸ºSUM()是在所有选定行上计算的,而WHERE是用于选择行。您需è¦åœ¨å•ç‹¬çš„查询中计算总和,然åŽå°†å…¶åŠ å…¥ã€‚

UPDATE purchase
JOIN (SELECT SUM(plan) AS plantotal FROM purchase) AS p1
    ON 4*(plan-1) <= plantotal
SET stat = '1'
WHERE id = '$id'

è¦ä½¿æ›´æ–°åŸºäºŽå…·æœ‰æ›´é«˜ID的所有行,您å¯ä»¥ä¸Žä¸€ä¸ªå­æŸ¥è¯¢ç»“åˆä½¿ç”¨ï¼Œè¯¥å­æŸ¥è¯¢èŽ·å–æ¯ç»„行的总数。

UPDATE purchase AS p
JOIN (SELECT p1.id AS id, SUM(p2.plan) AS plantotal
      FROM purchase AS p1
      JOIN purchase AS p2 ON p2.id > p1.id) AS p3
ON p3.id = p.id AND 4*(p.plan-1) <= p3.plantotal
SET stat = '1'