【问题标题】:How to use INSERT INTO SELECT ON DUPLICATE KEY UPDATE with IF statement如何在 IF 语句中使用 INSERT INTO SELECT ON DUPLICATE KEY UPDATE
【发布时间】:2019-12-09 05:34:15
【问题描述】:

在这里,我尝试在给定条件下对 MySQL 中的重复密钥更新进行 记录。 假设我有一个名为“Item”的表和另一个名为“Item_backup”的表,其中包含一组应插入原始“Item”表的备份记录。两个表的结构都是一样的。

当插入数据记录时,如果有任何重复键,那么我需要检查 insert_date 列,并且只有当“Item”表中的 insert_date 列小于“Item_backup”表中的 insert_date 列。

我使用的查询是,

INSERT INTO ITEM (item_number, price, quantity, insert_date)
SELECT ib.item_number, ib.price, ib.quantity, ib.insert_date 
FROM ITEM_backup ib
ON DUPLICATE KEY UPDATE
item_number = IF(@is_a_new_record := insert_date < ib.insert_date, ib.item_number, item_number),
price = IF(@is_a_new_record, ib.price, price),
quantity = IF(@is_a_new_record, ib.quantity, quantity),
insert_date = IF(@is_a_new_record, ib.insert_date, insert_date);

现在出现这样的错误, “SQL 错误:字段列表中的列 'insert_date' 不明确”

谁能指出这个查询有什么问题?

【问题讨论】:

  • 请添加项目的表定义(包括键)
  • CREATE TABLE ITEM ( item_number int(11) NOT NULL COMMENT 'Item number', price int(15) DEFAULT NULL COMMENT 'Item price', quantity int(10) DEFAULT NULL COMMENT 'Quantity', insert_date int(10) unsigned DEFAULT '0' COMMENT '最后插入日期', PRIMARY KEY (item_number) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Item';

标签: mysql database sql-insert on-duplicate-key


【解决方案1】:

终于,我找到了正确的答案。

INSERT INTO ITEM (item_number, price, quantity, insert_date)
SELECT ib.item_number, ib.price, ib.quantity, ib.insert_date 
FROM ITEM_backup ib
ON DUPLICATE KEY UPDATE
item_number = IF(@is_a_new_record := ITEM.insert_date < ib.insert_date, ib.item_number, ITEM.item_number),
price = IF(@is_a_new_record, ib.price, ITEM.price),
quantity = IF(@is_a_new_record, ib.quantity, ITEM.quantity),
insert_date = IF(@is_a_new_record, ib.insert_date, ITEM.insert_date);

【讨论】:

    猜你喜欢
    • 2011-01-29
    • 1970-01-01
    • 2010-12-15
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多