玛丽亚DB插入到..选择..在影响 0 行的重复键更新上


MariaDB INSERT INTO... SELECT... ON DUPLICATE KEY UPDATE affecting 0 rows

我在MariaDB中创建了下表

表创建

CREATE TABLE `email_templates_pending` (
  `template_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `template_name` varchar(100) NOT NULL,
  `template_data` text,
  `modify_type` varchar(16) NOT NULL,
  `modify_by` varchar(50) NOT NULL,
  `modify_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`template_id`),
  UNIQUE KEY `template_name` (`template_name`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

并在该表中插入了一行带有template_id = 1.我想使用以下INSERT INTO...SELECT...ON DUPLICATE KEY UPDATE语句更新该行

SQL 语句

INSERT INTO email_templates_pending
          (template_id, template_name, template_data,  modify_by,    modify_type) 
    SELECT template_id, template_name, template_data, 'test@test.com', 'Deleted'
        FROM email_templates WHERE template_id= '1' 
ON DUPLICATE KEY UPDATE modify_type='Deleted'

但是,当我运行语句时,它返回成功但带有0 rows affected.我有另一个类似的表,具有不同的列名称,可以按预期工作。我已经确保template_id是主键,所以我不确定还有什么问题?

email_templates_pending中有 1 行,但email_templates中没有行。

这可能是 0 行受到影响的原因。源表中没有行。

INSERT INTO email_templates_pending ...
SELECT ... FROM email_templates

如果您只想更新 id = 1,则可以使用以下命令:

INSERT INTO email_templates_pending (template_id, template_name, template_data, modify_by, modify_type) 
SELECT template_id, template_name, template_data, 'test@test.com', 'Deleted' FROM email_templates_pending 
ON DUPLICATE KEY UPDATE modify_type='Deleted';

如果只需要做 UPDATE,可以直接使用 UPDATE 语句也可以使用。

UPDATE email_templates_pending SET modify_type='Deleted' WHERE template_id= '1';

如果 id#1 存在并且已经标记为"已删除",您将正确获得"0 行受到影响"。

为了证明事实并非如此,让我们看看

SELECT template_id, template_name, template_data,  modify_by,    modify_type
    FROM email_templates WHERE template_id= '1' ;