gpt4 book ai didi

MySQL:使用 SUM 和 JOIN 进行更新

转载 作者:行者123 更新时间:2023-11-29 15:08:23 25 4
gpt4 key购买 nike

我正在尝试进行求和并将其存储在另一个表中。 SUM 很简单:

SELECT award.alias_id, 
SUM(award.points) AS points
FROM award
INNER JOIN achiever ON award.id = achiever.award_id

我现在想存储它。我弄清楚了如何逐行执行此操作:

UPDATE aliaspoint 
SET points = (SELECT SUM(award.points) AS points
FROM award
INNER JOIN achiever ON award.id = achiever.award_id
WHERE achiever.alias_id = 2000)
WHERE alias_id = 2000;

我认为这样的东西可能会起作用,但我得到:

ERROR 1111 (HY000): Invalid use of group function
<小时/>
UPDATE aliaspoint 
INNER JOIN achiever ON aliaspoint.alias_id = achiever.alias_id
INNER JOIN award ON achiever.award_id = award.id
SET aliaspoint.points = SUM(award.points)

还有一些表格定义可以提供帮助:

mysql> show create table aliaspoint;
| metaward_aliaspoint | CREATE TABLE `aliaspoint` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`alias_id` int(11) NOT NULL,
`points` double DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `alias_id` (`alias_id`),
KEY `aliaspoint_points` (`points`)
) ENGINE=MyISAM AUTO_INCREMENT=932081 DEFAULT CHARSET=latin1 |

mysql> show create table achiever;
| metaward_achiever | CREATE TABLE `achiever` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`modified` datetime NOT NULL,
`created` datetime NOT NULL,
`award_id` int(11) NOT NULL,
`alias_id` int(11) NOT NULL,
`count` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `achiever_award_id` (`award_id`),
KEY `achiever_alias_id` (`alias_id`)
) ENGINE=MyISAM AUTO_INCREMENT=87784996 DEFAULT CHARSET=utf8 |

mysql> show create table award;
| metaward_award | CREATE TABLE `award` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`points` double DEFAULT NULL,
PRIMARY KEY (`id`),
) ENGINE=MyISAM AUTO_INCREMENT=131398 DEFAULT CHARSET=utf8 |

最佳答案

您缺少以下位置的 GROUP BY 子句:

SET points = (SELECT SUM(award.points) AS points 
FROM award
INNER JOIN achiever ON award.id = achiever.award_id
WHERE achiever.alias_id = 2000)

关于 AWARDACHIEVER 表的信息不足,因此我建议在更新 UPDATE 语句之前对此进行测试:

  SELECT t.id, -- omit once confirmed data is correct
a.alias_id, -- omit once confirmed data is correct
SUM(t.points) AS points
FROM AWARD t
JOIN ACHIEVER a ON a.award_id = t.id
GROUP BY t.id, a.alias_id

一旦您知道求和正确,请更新 INSERT 语句:

SET points = (SELECT SUM(t.points)
FROM AWARD t
JOIN ACHIEVER a ON a.award_id = t.id
WHERE a.alias_id = 2000 --don't include if you don't need it
GROUP BY t.id, a.alias_id)

关于MySQL:使用 SUM 和 JOIN 进行更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1481096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com