mysql 用select 语句的查询结果当作 insert 语句需要插入的值

在实际使用中会遇到这样的场景,需要根据一个表里的内容在其他表中添加关联的数据,这时候就会用到

insert into {table_name} select x1,x2,x3... from {table_name2} where xxx

使用方法

1、通过select 语句找到在 table1 中需要的内容

select id, name, ... from table1 where id in (1, 2, 3, ...);

2、用select 语句 替换 insert 语句中的 values 

insert into table2 select id,name... from table1 where xxx

3、如果需要插入的值 table1 里面没有 就直接在 select 语句中按照 table2 的字段顺序添加上就可以了

//其中 100 是table2 表中的第三个字段的值
//'张三' 是table2 表中的第四个字段的值
insert into table2 select id,name,100,'张三'... from table1 where xxx

猜你喜欢

转载自blog.csdn.net/wuchenlhy/article/details/110130747
今日推荐