SQL insert into select 用法
一張存在的表,插入的新數據來源別的表時,可以使用insert into select
語法。
1、兩種語法
1、表數據
user表
id name age
1 test 10
2 test1 20
3 test2 14
4 test3 16
user_copy表
user_copy
表結構與 user
表一樣,只不過數據為空。
address 表
id city address user_id
1 廣州市 天河區 2
2 肇慶市 端州區 1
3 汕頭市 朝陽區 1
4 肇慶市 鼎湖區 3
5 汕頭市 從化區 3
6 廣州市 白雲區 2
address
與user
屬於多對一的關系。
2、語法1
如果兩表的結構完全相同,可以直接使用以下的簡易語法。
insert into 表名2 select * from 表名1 where 條件
例子
上文 user
表 與user_copy
表結構一樣,因此例子如下:
insert into user_copy select * from user u where u.id in(1,2)
id
為1、2的數據便成功插入到user_copy
表中。
結果如下:
3、語法2
如果只希望插入希望的列,或者特定的列指定為常量,語法如下
insert into 表名2(列名1, 列名2, 列名3) select 返回值1,返回值2,常量 as 返回值3 from 表名1,表名3,表名4 where 條件
注意:返回值要與表2的列名一一對應。
例子
向user_copy
插入特定的name
和age
, age
指定為15,例子如下:
insert into user_copy(name, age) select u.name as name, 15 as age
from user u, address a
where u.id = a.user_id and a.address = '從化區'
結果如下:
根據需求選擇對應的語法。