我有两张桌子。 用户1:
UserID HolidayCity ValidFrom ValidTo
1 NULL '1900-01-01' '2017-05-09'
1 NULL '2017-05-09' NULL
2 NULL '1900-01-01' '2017-05-09'
2 NULL '2017-05-09' NULL
Users2:
UserID CityID
1 33
2 55
我需要从第一个表更新HolidayCity列,其中CityID列中的值来自第二个表中的每个UserID,但只有那些记录,其中ValidTo IS NULL ,以便生成表Users1将是:
UserID HolidayCity ValidFrom ValidTo
1 NULL '1900-01-01' '2017-05-09'
1 33 '2017-05-09' NULL
2 NULL '1900-01-01' '2017-05-09'
2 55 '2017-05-09' NULL
你能告诉我怎么做吗?
答案 0 :(得分:3)
这是一个简单的inner join
update u
set u.holidaycity=c.cityid
from users1 u
inner join users2 c
on u.userid = c.userid
and u.validto is null
答案 1 :(得分:0)
UPDATE U1
SET U1.HolidayCity = U2.CityID
FROM Users1 AS U1
INNER JOIN Users2 AS U2 ON U2.UserId = U1.UserId
WHERE U1.ValidTo IS NULL
如果您对上述代码有任何疑问,请尽快扩展,但这是一种简单的更新格式。
答案 2 :(得分:0)
试试这个:
update a
set a.HolidayCity = b.CityID
FROM Users1 AS a INNER JOIN
Users2 AS b ON a.UserId = b.UserId
WHERE (a.ValidTo IS NULL)
答案 3 :(得分:0)
将内容从一个表复制到另一个表的简单方法如下:
UPDATE table2
SET table2.col1 = table1.col1,
table2.col2 = table1.col2,
...
FROM table1, table2
WHERE table1.memberid = table2.memberid