![](/img/trans.png)
[英]JOIN rows from 3 tables WHERE tableA.column1 = tableB.column1 = tableC.column1
[英]Set column values in TableA to corresponding values from TableB if some value exist in TableC
我有一个TableA,我刚刚将两列添加到StartDate和StopDate。 它还包含UserName列。
我想用同样具有StartDate和StopDate的TableB中的值填充它。 TableB的另一列称为UserId。
TableC有两列,Id和Name。
这是我想做的,用某种伪代码解释:
for each row in TableB, where TableB.UserId exists in TableC.Id, take the corresponding row in TableA where TableA.UserName = TableC.Name and set the TableA.StartDate = TableB.StartDate & TableA.StopDate = TableB.StopDate.
我试图创建一个可以执行此操作的join语句,但是结果有点尴尬。 帮助将不胜感激。
编辑:我曾尝试:
UPDATE TableA
SET STARTDATE = (
SELECT TableB.StartDate
FROM TableB
WHERE TableB.UserId = (??? what should I write here)?
然后对于StopDate同样
您可以使用“ update-from”语法来实现。 *我看到您已经解决了您的问题,但我将其发布为可能的选择。
declare @TableA table (id int identity(1, 1), startDate datetime, stopDate datetime, userName varchar(20))
declare @TableB table (id int identity(1, 1), startDate datetime, stopDate datetime, userId int)
declare @TableC table (userId int, userName varchar(20))
insert into @TableA (userName)
select 'A' union all select 'B'
insert into @TableB (userId, startDate, stopDate)
select 1, '2015-01-01', '2015-01-31' union all select 2, '2015-12-01', '2015-12-31'
insert into @TableC
select 1, 'A' union all select 2, 'B'
update
A
set
A.startDate = B.startDate,
A.stopDate = B.stopDate
from
@TableA A
inner join @TableC C on C.userName = A.userName
inner join @TableB B on B.userId = C.userId
select
*
from
@TableA
我解决了,这是我的解决方案
UPDATE TableA
SET StartDate = up.StartDate, EndDate = up.EndDate
FROM TableB up WHERE up.UserID = (SELECT Id from TableC u where u.Name = TableA.UserName)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.