秦之声

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  26 随笔 :: 0 文章 :: 0 评论 :: 65664 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

多张表UPDATE用法

sql 语句多张表UPDATE用法
一、当用一个表中的数据来更新另一个表中的数据,T-SQL提供多种写法(下面列出了二种),但建议用第一种写法,虽然传统,但结构清晰。
并且要注意,当用一个表中的数据来更新另一个表中的数据时,二个表一定要有关联!
1.
update t1 set t1.c2 = t2.c2
from t2
where t1.c1 = t2.c1
2.
Update t1 set t1.c2 = t2.c2
from t1 inner join t2 on t1.c1 = t2.c1
二、FROM 子句中指定的表的别名不能作为 SET column_name 子句中被修改字段的限定符使用。
UPDATE titles
SET t.ytd_sales = t.ytd_sales + s.qty
FROM titles t, sales s
WHERE t.title_id = s.title_id
AND s.ord_date = (SELECT MAX(sales.ord_date) FROM sales)

若要使上例合法,请从列名中删除别名 t 或使用本身的表名。
1.
UPDATE titles
SET ytd_sales = t.ytd_sales + s.qty
FROM titles t, sales s
WHERE t.title_id = s.title_id
AND s.ord_date = (SELECT MAX(sales.ord_date) FROM sales)

2.
UPDATE titles
SET titles.ytd_sales = t.ytd_sales + s.qty
FROM titles t, sales s
WHERE t.title_id = s.title_id
AND s.ord_date = (SELECT MAX(sales.ord_date) FROM sales)

EXAMPLE
update item_master i set i.contral_ma= ( select max(b.control_ma) from base_complex b where b.code=i.hs_code );

更新一列:
update mytab a set name=(select b.name from goal b where b.id=a.id)
where exists (select 1 from goal b where b.id=a.id);
更新多列:
update mytab a
set (name,address)=(select b.name,b.address
from goal b
where b.id=a.id)
where exists (select 1
from goal b
where b.id=a.id )
特别是要注意exists后面的语句:)这会让目标行不至于为NULL

更新update多个关联表的SQL写法:
update customers a
set city_name=(select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id)
where exists (select 1
from tmp_cust_city b
where b.customer_id=a.customer_id
)
update 超过2个值
update customers a
set (city_name,customer_type)=(select b.city_name,b.customer_type
from tmp_cust_city b
where b.customer_id=a.customer_id)
where exists (select 1
from tmp_cust_city b
where b.customer_id=a.customer_id
)

posted on   秦之声  阅读(40122)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示