I'm familiar with the following use of the command:
INSERT INTO mytable
SELECT *
FROM other_table
This works fine when the tables are identical in terms of layout.
What I'd like to do is something like:
INSERT INTO mytable
SELECT *
FROM other_table ON DUPLICATE KEY UPDATE
This fails with a syntax error:
MySQL Error: 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 ON QUERY INSERT INTO mytable SELECT * FROM other_table ON DUPLICATE KEY UPDATE
I can't find any docs that describe this.
Yes, absolutely, but check your syntax.
Insert Ignore statement in MySQL has a special feature that ignores the invalid rows whenever we are inserting single or multiple rows into a table. We can understand it with the following explanation, where a table contains a primary key column. The primary key column cannot stores duplicate values into a table.
INSERT INTO SELECT statement in SQL Server is used to copy data from the source table and insert it into the destination table. The SELECT INTO statement in SQL Server is used to copy data from one (source) table to a new table. INSERT INTO SELECT requires the destination table to be pre-defined.
INTO' creates the destination table, it exclusively owns that table and is quicker compared to the 'INSERT … SELECT'. Because the 'INSERT … SELECT' inserts data into an existing table, it is slower and requires more resources due to the higher number of logical reads and greater transaction log usage.
Your statement is incomplete:
INSERT INTO mytable
SELECT *
FROM other_table ON DUPLICATE KEY UPDATE
The syntax requires that you need to finish the UPDATE
part by listing which columns to update with which values.
UPDATE:
This ought to work for your particular example:
INSERT INTO mytable2 (id, name, `key`)
SELECT id, name, `key` FROM mytable b
ON DUPLICATE KEY UPDATE name = b.name
The changes are:
SELECT
part.key
, since "key" is a reserved word in MySQL.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With