SQL Server查询使用另一个表值更新一个表列值

时间:2016-05-14 09:04:23

标签: sql-server sql-server-2012

我希望one table更新another table列值。我有两张表,Users, UserProfile我在两张表中都有MobileNumber列。所以我想从Users更新UserProfile表移动电话号码。 UserProfile表中可能存在重复的移动号码。所以我想避免Users表中的重复值。如果已存在MobileNumber,则无需更新。

这是我的query

update Users 
set MobileNumber = up.MobileNumber
from Users u 
left join UserProfile up on u.UserID = up.UserID
where up.MobileNumber not in (select ISNULL(MobileNumber, '') from Users);

但它无法正常工作。在UserProfile表中,有些记录在Null中包含MobileNumber值。如何在不重复的情况下更新此列?

2 个答案:

答案 0 :(得分:1)

最后我得到了解决方案

Update u set u.MobileNumber = up.MobileNumber
FROM Users u
JOIN(
 SELECT MobileNumber, MIn(UserId) AS UsID FROm UserProfile
 group by MobileNumber
) up
on u.UserID = up.UsID

答案 1 :(得分:0)

MERGE将帮助您:

MERGE Users as target
USING (
    SELECT DISTINCT up.UserID, up.MobileNumber 
    FROM UserProfile up 
    WHERE up.MobileNumber NOT IN (SELECT MobileNumber FROM Users WHERE MobileNumber IS NOT NULL)) as source
ON target.UserID = source.UserID
WHEN MATCHED AND target.MobileNumber IS NULL THEN
    UPDATE SET MobileNumber = source.MobileNumber;

但是,如果某些MobileNumber的内容超过1 userid,则必须将SELECT DISTINCT UserID, MobileNumber FROM UserProfile WHERE MobileNumber IS NOT NULL部分更改为SELECT DISTINCT UserID, MAX(MobileNumber) FROM UserProfile WHERE MobileNumber IS NOT NULL GROUP BY UserID之类的内容,或者编写自己的查询选择你需要的东西。