Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using INSERT INTO SELECT when table structures do not match in MySQL

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.

like image 209
julio Avatar asked Jun 03 '11 16:06

julio


People also ask

Can insert be used with select?

Yes, absolutely, but check your syntax.

How does insert ignore work?

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.

What is the difference between insert into to select?

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.

Which is faster insert into or select into?

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.


1 Answers

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:

  • remove the parentheses around the column names in the SELECT part.
  • quote the column name key, since "key" is a reserved word in MySQL.
like image 191
Ted Hopp Avatar answered Sep 22 '22 07:09

Ted Hopp