sql update多表关联

本文介绍了如何使用SQL更新表中数据的方法,并通过具体案例展示了常见的语法错误及其修正方案。通过对两张表进行联表更新操作,详细解释了正确的SQL语句写法。

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

一、建立测试表
CREATE TABLE t_user (
ID int identity PRIMARY KEY,
UserID varchar(50) not null,
UserName varchar(50) null,
deptID int not null,
phone varchar(50) null,
fax varchar(50) null
)

CREATE TABLE t_dept (
ID int identity PRIMARY KEY,
DeptName varchar(50) null,
phone varchar(50) null,
fax varchar(50) null
)

INSERT t_user
SELECT N'001',N'张三',1,N'88888001',N'99999001'
UNION  ALL SELECT N'002',N'李四',2,N'88888002',N'99999002'
UNION  ALL SELECT N'003',N'王五',2,N'88888003',N'99999003'
UNION  ALL SELECT N'004',N'赵六',3,N'88888004',N'99999004'

INSERT t_dept
SELECT N'开发部',N'88888011',N'99999011'
UNION  ALL SELECT N'市场部',N'88888022',N'99999022'
UNION  ALL SELECT N'售后部',N'88888033',N'99999033'

二、sql更新(每次执行update后都还原t_user数据)

1、update t_user set u.phone=d.phone, u.fax=d.fax from t_user u, t_dept d where u.deptID=d.ID

报错:无法绑定由多个部分组成的标识符 "u.phone"。
2、update u set u.phone=d.phone, u.fax=d.fax from t_user u, t_dept d where u.deptID=d.ID

 

 正确

select * from t_user

 

 ID UserID UserName deptID phone fax
 1 001 张三 1 88888011 99999011
 2 002 李四 2 88888022 99999022
 3 003 王五 2 88888022 99999022
 4 004 赵六 3 88888033 99999033

 

 

3、update t_user u set u.phone=d.phone, u.fax=d.fax from t_dept d where u.deptID=d.ID

报错:'u' 附近有语法错误。

4、update t_user set phone=d.phone, fax=d.fax from t_dept d where deptID=d.ID

正确,结果同2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值