开发者

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

开发者 https://www.devze.com 2022-12-24 23:56 出处:网络
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.

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 l开发者_运维知识库ike 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

0

精彩评论

暂无评论...
验证码 换一张
取 消