我希望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
值。如何在不重复的情况下更新此列?
答案 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
之类的内容,或者编写自己的查询选择你需要的东西。