【问题标题】:MYSQL: Is there a way to Insert Values from another Table with ON DUPLICATE KEY UPDATE?MYSQL:有没有办法使用 ON DUPLICATE KEY UPDATE 从另一个表中插入值?
【发布时间】:2021-06-02 05:49:28
【问题描述】:

我的问题: 有没有办法使用 ON DUPLICATE KEY UPDATE 从另一个表中插入值?但是我在这个语句中也使用了 SUM

这是我的例子:

INSERT INTO currencyStatistics (note, currency, amount) 
SELECT note, currency, SUM(amount) as amount2 
FROM currency 
WHERE date<1612188495 
GROUP BY note 
ON DUPLICATE KEY UPDATE amount=amount+amount2;

MySQL 返回错误:“#1054 - '字段列表'中的未知列 'amount2'”

奖金信息:表currencyStatistics 有4 列:note、currency、amount 和lastUpdate。 我没有在插入时添加最后一个更新,导致其时间戳默认为“current_timestamp(6)”和额外的“ON UPDATE CURRENT_TIMESTAMP(6)”

有人可以帮我解决这个问题吗?

问候我

编辑:添加正确的错误信息

【问题讨论】:

  • 该语句不能抛出该错误 - 货币别名为 c 吗?
  • 嗨鲑鱼,你是对的,我刚刚复制了另一个尝试这个脚本的旧错误消息,很抱歉

标签: mysql sum duplicates sql-insert where-clause


【解决方案1】:
INSERT INTO currencyStatistics (note, currency, amount) 
SELECT note, currency, SUM(amount)
FROM currency 
WHERE date<1612188495 
GROUP BY note 
ON DUPLICATE KEY 
UPDATE amount = amount + VALUES(amount);

在更新中:

  • amount 是更新表的列 (currencyStatistics)
  • VALUES(amount) 是在没有重复的情况下将插入到 amount 中的值(即 SUM(amount) 值)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 2018-10-26
    • 2011-02-12
    • 1970-01-01
    相关资源
    最近更新 更多