2016-03-10 29 views
1
密鑰更新

我創建了下表中MariaDB的MariaDB的INSERT INTO ... SELECT ...對重複影響0行

創建表

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。我想更新下面

SQL語句使用以下INSERT INTO...SELECT...ON DUPLICATE KEY UPDATE語句行

INSERT INTO email_templates_pending 
      (template_id, template_name, template_data, modify_by, modify_type) 
    SELECT template_id, template_name, template_data, '[email protected]', 'Deleted' 
     FROM email_templates WHERE template_id= '1' 
ON DUPLICATE KEY UPDATE modify_type='Deleted' 

然而,當我運行該語句返回成功,但與0 rows affected。我有另一個類似的表具有不同的列名,按預期工作。我確保template_id是主鍵,所以我不確定還有什麼問題可以解決?

回答

1

您在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, '[email protected]', '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'; 
+0

輸出是否可以更新語法,所以它不依賴於email_templates表? – Jester

+0

爲什麼不只是使用更新? @Jester –

+0

代碼的架構方式實際上需要從email_template表中獲取值,前提是它不存在於email_template_pending表中。你是否建議在INSERT SELECT之後運行第二個UPDATE語句? – Jester

0

如果ID#1存在已經被標記爲 「已刪除」,你會得到正確的 「受影響的0行」。

爲了證明這不是這種情況,讓我們來看看從

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