2016-05-14 102 views
1

我想從another table更新one table列值。我有兩個表,即Users, UserProfile我在這兩個表中有MobileNumber列。所以我想從UserProfile更新Users表手機號碼。 UserProfile表中可能有重複的移動號碼。所以我想避免Users表中的重複值。如果已經存在MobileNumber則不需要更新。用另一個表值更新一個表列值的SQL Server查詢

這裏是我的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表中有一些記錄,其中包含NullMobileNumber。我如何更新此列而不重複?

+1

您所查詢的完美。你面臨的問題在哪裏。@ Ajay –

+0

請澄清。用戶中每個用戶有1條記錄,UserProfile中每個用戶有多條記錄? –

+0

@ P.Salmon對不起。在userprofile表中,mobilenumber對於多個用戶可能是相同的。在UserProfile中,對於單個用戶只有一條記錄,例如'User.UserId = UserProfile.UserId',您將只能找到一條記錄。 –

回答

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 
+0

太棒了,你找到答案! :) – gofr1

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; 

但是,如果你對某些userid的得到更多的則1 MobileNumber必須更改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或寫自己的查詢來選擇你所需要的。

+0

感謝您的回覆。我試過你的答案。但它仍然在用戶的'用戶'表中添加重複的手機號碼。在'Users&UserProfile'中,對於單個用戶只有一條記錄,比如'User.UserId = UserProfile.UserId',你只能找到一條記錄。但userprofile表中的許多用戶的手機號碼可能相同。 –

+0

更新'MobileNumber'時,我想查看天氣情況,'MobileNumber'在'User'表中不存在。如果存在,則不需要更新。 –

+0

然後將EXISTS語句添加到源查詢中。或者嘗試從我的答案中使用查詢,我已編輯答案 – gofr1