SQL insert into select 用法


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

addressuser屬於多對一的關系。

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表中。

結果如下:

image-20210108165855760

3、語法2

如果只希望插入希望的列,或者特定的列指定為常量,語法如下

insert into 表名2(列名1, 列名2, 列名3) select 返回值1,返回值2,常量 as 返回值3 from 表名1,表名3,表名4 where 條件

注意:返回值要與表2的列名一一對應。

例子

user_copy插入特定的nameage, 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 = '從化區'

結果如下:

image-20210108171707902
根據需求選擇對應的語法。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM