我正在尝试在 mysql 5.5 中执行以下查询
INSERT INTO countingTable( image_count, article_id )
SELECT COUNT( article_id ) AS sum, article_id
FROM imageTable
ON DUPLICATE KEY UPDATE image_count = VALUES(sum)
Run Code Online (Sandbox Code Playgroud)
但这给出了错误:
#1054 - Unknown column 'sum' in 'field list'
Run Code Online (Sandbox Code Playgroud)
编辑以更好地解释我喜欢做什么:
计数表结构:
CREATE TABLE IF NOT EXISTS `countigTable` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`plakat` varchar(255) COLLATE utf8_bin DEFAULT NULL,
`image_count` bigint(20) DEFAULT NULL,
`trailer_count` bigint(20) DEFAULT NULL,
`actor_count` bigint(20) DEFAULT NULL,
.... (many more counting fields)
`article_id` bigint(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `article_id` (`article_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1 ;
Run Code Online (Sandbox Code Playgroud)
imageTable 具有以下结构:
CREATE TABLE IF NOT EXISTS `imageTable` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`article_id` bigint(20) DEFAULT NULL,
`image_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `article_id` (`article_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1 ;
Run Code Online (Sandbox Code Playgroud)
(imageTable 基本上是多对多关系的参考表)
计数表已经有引用 article_id 的行。现在我喜欢计算所有相关图像并在计数表中插入或更新它。
后来我需要为拖车计数、演员计数等提供相同的东西。
如果这是第一次完成,countingTable 将被触发器更新。
这个想法是,拥有这张表,所以我不需要加入所有关系只是为了计算它们是否存在。(因为我的项目一直需要计数)
使用UPDATE image_count = VALUES(image_count)
.
VALUES()
需要您插入的列中的名称,而不是查询中的别名。查询应该是:
INSERT INTO countingTable (image_count, article_id)
SELECT COUNT(article_id) AS sum, article_id
FROM imageTable
GROUP BY article_id -- I suppose you skipped that line?
ON DUPLICATE KEY UPDATE image_count = VALUES(image_count) ;
Run Code Online (Sandbox Code Playgroud)
如果要将新值添加到现有值中,请使用:
...
ON DUPLICATE KEY UPDATE image_count = image_count + VALUES(image_count) ;
Run Code Online (Sandbox Code Playgroud)