简体   繁体   中英

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

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?

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)
INSERT INTO `table2` (place, event, myYear)
SELECT place, event, 2010
FROM table1

Edit: bah, didn't get the answer posted notification :P

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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