简体   繁体   中英

Mysql Insert data from one table to another table

INSERT INTO table2 (firstname, lastname, middlename) SELECT firstname, lastname FROM table1 WHERE id = 1

How can I insert data for table2 'middlename' column? In my table1 there is only two column 'firstname' and 'lastname'

Remove the middlename column from the list:

INSERT INTO table2 (firstname,lastname) 
SELECT firstname, lastname FROM table1 WHERE id = 1

试试这个查询

INSERT INTO table2 (firstname, lastname, middlename) SELECT firstname, lastname, "NA" FROM table1 WHERE id = 1
INSERT INTO table2 (firstname,lastname) SELECT firstname, lastname FROM table1

将table2中的中间名留空,因为您没有记录

If it's a mandatory column (ie NOT NULL and no default defined), you'll have to select a constant. Something like

insert into table2 (firstname, lastname, middlename)
select firstname, lastname, 'N/A' from table1 where id = 1;

If the column is optional, omit the column from the column list. Like

insert into table2 (firstname, lastname)
select firstname, lastname from table1 where id = 1;

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