Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I INSERT INTO from one mysql table into another table and set the value of one column?

Tags:

mysql

insert

I need to insert data from table1 into table2. However, I would like to set the myYear column in table2 to 2010. But, there isn't a myYear Column in table1.

So, my basic insert looks like:

INSERT INTO  `table2` ( place, event ) 
SELECT place, event
FROM table1

Roughly, I'd like to do something like the following:

INSERT INTO `table2` ( place, event, SET myYear='2010' )
...

Is there a way to set the column value in the insert statement?

like image 387
Laxmidi Avatar asked Mar 31 '10 00:03

Laxmidi


People also ask

How can I insert values from one table to another table in MySQL?

The SQL 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 match. Note: The existing records in the target table are unaffected.

How do I transfer data from one table to another in SQL?

Using SQL Server Management StudioOpen the table with columns you want to copy and the one you want to copy into by right-clicking the tables, and then clicking Design. Click the tab for the table with the columns you want to copy and select those columns. From the Edit menu, click Copy.


1 Answers

The following should do it:

INSERT INTO `table2` (place, event, myYear) 
SELECT place, event, '2010'
FROM   table1;

Basic test case:

CREATE TABLE t1 (a int, b int);
CREATE TABLE t2 (c int);

INSERT INTO t2 VALUES (1),(2),(3),(4),(5);

INSERT INTO t1 SELECT c, 100 FROM t2;

SELECT * FROM t1;

+------+------+
| a    | b    |
+------+------+
|    1 |  100 | 
|    2 |  100 | 
|    3 |  100 | 
|    4 |  100 | 
|    5 |  100 | 
+------+------+
5 rows in set (0.00 sec)
like image 129
Daniel Vassallo Avatar answered Oct 16 '22 17:10

Daniel Vassallo