MySQL: Copy table to another table with an extra column

帅比萌擦擦* 提交于 2021-02-10 05:49:09

问题


I have two tables, tab1 and tab2.

tab2 has all of the columns of tab1 but with an extra column for a timestamp. What I want to do is copy all of the rows from tab1 into tab2 and input the same time thae timestamp column for all rows that I insert. I can get and input the time fine, but I'm confused how to copy and insert data and fill in the last column with the timestamp for all of the rows that I inserted.

So I want to do:

Insert into tab2 select * from tab1

but I also want to add data for that final column in tab2, how can I do this?


回答1:


You could add the timestamp to the select list so the column lists of both tables would match:

INSERT INTO tab2
SELECT *, CURRENT_TIMESTAMP()
FROM   tab1

EDIT
To answer the question in the comment - you don't have to use CURRENT_TIMESTAMP(). Any expression returning a timestamp would do. You could use a hard-coded timestamp:

INSERT INTO tab2
SELECT *, TIMESTAMP('2017-07-07 19:43:00')
FROM   tab1


来源:https://stackoverflow.com/questions/42425773/mysql-copy-table-to-another-table-with-an-extra-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!