MySQL INSERT INTO…VALUE和SELECT与几个字段

时间:2018-07-19 10:29:20

标签: mysql sql mariadb

我需要执行以下操作:

将INERT INTO表1(field1,field2,field3,field4,field5)      值(“ customvalue1”,SELECT field2,field3,field4,field5 FROM table2 WHERE condition = true)

有办法吗?最好的方法是什么?

3 个答案:

答案 0 :(得分:4)

您可以使用select语句定义常量值:

INSERT INTO table1 (field1,field2,field3,field4,field5) 
   SELECT "customvalue1", field2, field3, field4, field5 
   FROM table2 
   WHERE condition=true;

答案 1 :(得分:1)

这称为根据条件将数据从一个表插入到另一表

create table table1
(id int,
name varchar(100)
)
;
create table table2
(id int,
 name varchar(100),
 salary double(10,2)
)
;
insert into table1 values(1,'A'),(2,'B'),(3,'C');

insert into table2(id,name,salary) 
select id,name,6000 from table1 where table1.name='A'

http://sqlfiddle.com/#!9/8b30fb/1

答案 2 :(得分:1)

我认为这对您有帮助

  INSERT INTO firsttable (field1,field2,field3,field4,field5) 
   SELECT "customvalue1", field2, field3, field4, field5 
   FROM secondtable
   WHERE condition;