11

我正在从 tableONE 查询并尝试将结果集插入到 tableTWO 中。这有时会导致 tableTWO 中出现重复键错误。所以我想ON DUPLICATE KEY UPDATE从 tableONE 结果集中使用新确定的值,而不是用ON DUPLICATE KEY UPDATE columnA = columnA.

INSERT INTO `simple_crimecount` (`date` , `city` , `crimecount`)(
    SELECT 
        `date`, 
        `city`,
        count(`crime_id`) AS `determined_crimecount`
    FROM `big_log_of_crimes`
    GROUP BY `date`, `city`
) ON DUPLICATE KEY UPDATE `crimecount` = `determined_crimecount`;
# instead of [ON DUPLICATE KEY UPDATE `crimecount` = `crimecount`];

它返回一个错误,说明以下内容

Unknown column 'determined_crimecount' in 'field list'
4

1 回答 1

28

问题是在重复键子句中,您不能使用任何分组函数(例如COUNT。但是,有一种简单的方法可以解决这个问题。您只需将COUNT(crime_id)调用结果分配给一个变量,您可以在重复键中使用该变量子句。您的插入语句将如下所示:

INSERT INTO `simple_crimecount` (`date` , `city` , `crimecount`)(
    SELECT 
        `date`, 
        `city`,
        @determined_crimecount := count(`crime_id`) AS `determined_crimecount`
    FROM `big_log_of_crimes`
    GROUP BY `date`, `city`
) ON DUPLICATE KEY UPDATE `crimecount` = @determined_crimecount;

我创建了一个 SQL Fiddle,向您展示它是如何工作的:SQL-Fiddle


您也可以使用UPDATE crimecount = VALUES(crimecount)并且没有变量:

INSERT INTO `simple_crimecount` (`date` , `city` , `crimecount`)(
    SELECT 
        `date`, 
        `city`,
        count(`crime_id`) AS `determined_crimecount`
    FROM `big_log_of_crimes`
    GROUP BY `date`, `city`
) ON DUPLICATE KEY UPDATE `crimecount` = VALUES(crimecount);

请参阅SQL-Fiddle-2

于 2013-06-06T07:51:59.337 回答