简体   繁体   English

如何在 INSERT SELECT 语句中使用 UPDATE

[英]How to use UPDATE in INSERT SELECT statement

I want to insert records from table2 to table1.我想从 table2 插入记录到 table1。 I need to replace the records if a duplicate in the primary key is found.如果在主键中找到重复项,我需要替换记录。 The primary key of a type string .类型string的主键。

So my statement look like ( name is primary key and it is a string . Duplicate rows can arise from table2 , which I want to update):所以我的语句看起来像( name是主键,它是一个string 。重复行可能来自table2 ,我想更新):

INSERT INTO `myscheme1`.`table1`
(`table1`.`name`,
    `table1`.`id`,
    `table1`.`history`)

SELECT `table2`.`name`,
    `table2`.`id`,
    `table2`.`history`
FROM `myscheme2`.`table2`;

Where to add UPDATE ?在哪里添加UPDATE If I can not use UPDATE , can you clarify how to use ON DUPLICATE KEY UPDATE ?如果我不能使用UPDATE ,你能说明如何使用ON DUPLICATE KEY UPDATE吗?

Because I do not get how to apply it?因为我不明白如何应用它? I do not know the new string of the primary key that I should update the old one with (it is being read by the command and I have many duplicate cases).我不知道我应该用什么来更新旧的主键的新字符串(它正在被命令读取并且我有很多重复的情况)。 So this example: below assumes I know what is the new value that I should input if a duplicate happens.所以这个例子:下面假设我知道如果发生重复,我应该输入的新值是什么。

I prefer to use UPDATE so it replaces the old record with the new automatically.我更喜欢使用UPDATE因此它会自动用新记录替换旧记录。

INSERT INTO 
   devices(name) 
VALUES 
   ('Printer') 
ON DUPLICATE KEY UPDATE name = 'Printer';

Can you please show me how to edit my command syntax if I want to use UPDATE or ON DUPLICATE KEY UPDATE ?如果我想使用UPDATEON DUPLICATE KEY UPDATE你能告诉我如何编辑我的命令语法吗?

You use ON DUPLICATE KEY UPDATE the same way whether the new values are coming from SELECT or VALUES .无论新值来自SELECT还是VALUES您都可以以相同的方式使用ON DUPLICATE KEY UPDATE

INSERT INTO `myscheme1`.`table1`
(`table1`.`name`, `table1`.`id`,  `table1`.`history`)
SELECT `table2`.`name`, `table2`.`id`, `table2`.`history`
FROM `myscheme2`.`table2`
ON DUPLICATE KEY UPDATE id = VALUES(id), history = VALUES(history);

If table1 has the same name as a row in table2 , the other columns will be copied into that row.如果table1table2的行具有相同的名称,则其他列将被复制到该行中。

You don't need to include the name column in ON DUPLICATE KEY .您不需要在ON DUPLICATE KEY包含name列。 It already has the value from the other table, since that's what makes it a duplicate.它已经具有另一个表中的值,因为这就是它重复的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM