0

我正在尝试进行 SUM 并将其存储在另一个表中。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 |
4

1 回答 1

1

您缺少以下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) 

AWARD和表上没有足够的信息ACHIEVER,所以我建议在更新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)
于 2009-09-26T15:45:21.513 回答