insert into select 跟 select into 以及 update另一张表内容的用法和区别

本文介绍了SQL中的三种常用数据操作方法:使用insertintoselect从一个表复制数据到另一个已存在的表;使用selectinto从一个表复制数据并创建新表;使用update更新一个表的数据为另一个表的数据。详细解释了每种方法的语法、注意事项及其应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    SQL简单语句查询中经常需要用到1.将一张表中的内容复制到另一张表;2.或者将查询的内容插入到指定表;3.或者将一个表中部分内容更新成另一张表中的内容),这时了解一下insert into selectselect into 以及 update另一张表内容的用法和区别是及有用的 大笑

、insert into select 语句:

语法:

insert into table1 (列1,列2,...) select value1,value2,... from table2 where ...
--或者:
insert into tabel1 select * from tabel2 where ... 
--将table2中符合条件的值插入(复制)到tabel1中去.

注意事项:

    (1)要求目标表tabel1必须存在,并且字段(列1,列2...)也必须存在。

    (2)注意目标表table1的主键约束,如果table1有主键而且不为空,列1,列2...中必须包括主键

    (3)注意语法,不要加values,不要和插入一条数据的SQL语句混淆了,不要写成:

insert into table1(列1,列2,...) values(select value1,value2,... from table2 where ...) 

、select into 语句:

语法:

select value1, value2,... into table1 from table2
--将table2中符合条件的值插入(复制)到tabel1中去.

注意事项:

    要求目标表table1不存在,因为再插入时会自动创建表table1,并将table2中制定的字段数据复制到table1中去。

、update(将一张表中的数据更新成另一张表中对应的数据):

语法:

update table1
set table1.列1=table2.列1,table1.列2=table2.列2
from table2 where table1.id=table2.id
--或者
update table1
set table1.列1=t2.列1,table1.列2=t2.列2
from table2 t2 where table1.id=t2.id

例如:

update [PS].[T_Bas_WaterOutput]
set  [PS].[T_Bas_WaterOutput].Longitude = t2.Longitude,[PS].[T_Bas_WaterOutput].Latitude=t2.Latitude
from [PS].[T_Bas_Equipment]  t2 where [PS].[T_Bas_WaterOutput] .OutportCode = t2.OutportCode
--将[PS].[T_Bas_WaterOutput]表中的Longitude,Latitude更新成[PS].[T_Bas_Equipment]表中Longitude,Latitude对应的值。

出处:http://blog.sina.com.cn/s/blog_7c7ec19b0100u6vb.html



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值