Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql insert the results of a select

I would like to know if I can run a request like that:

INSERT INTO t2 (a, b)  VALUES (  SELECT a, b  FROM `t1` AS o  WHERE o.id NOT   IN (   SELECT a   FROM t2    ) ) 

The idea is to fill the t2 with some data from the t1, but I must be wrong on the syntax.

Thanks for your help

like image 553
Roch Avatar asked Dec 17 '10 17:12

Roch


People also ask

How can insert selected values in a table in MySQL?

The MySQL INSERT INTO SELECT Statement The INSERT INTO SELECT statement copies data from one table and inserts it into another table. The INSERT INTO SELECT statement requires that the data types in source and target tables matches. Note: The existing records in the target table are unaffected.

Can insert be used with select?

You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.

What does insert query return in MySQL?

6 Answers. Show activity on this post. INSERT just returns true or false. to actually return something useful, you will need a SELECT or similar query.


1 Answers

You don't use the VALUES keyword when inserting from a SELECT statement.

INSERT INTO t2 (a, b)   SELECT a, b  FROM `t1` AS o  WHERE o.id NOT   IN (   SELECT a   FROM t2    ) 
like image 50
Joe Stefanelli Avatar answered Oct 03 '22 03:10

Joe Stefanelli