SQL Server UPDATE与左连接?

时间:2014-07-14 09:17:57

标签: sql sql-server sql-update left-join

我正在尝试更新一个表,这个表有多对一的关系。该表包含可以很多的成员资格,并且它们链接到一个人,即一个人。

会员资格可以是客户或从业者,因此他们拥有客户ID或从业者ID。

请询问您是否需要更多信息,以下是我在下面的尝试,我在UPDATE下尝试了所有左边的连接并且没有来自,但我已经发布了这个示例,因为我认为它最好显示什么我试图这样做。

UPDATE 
    MembershipUser AS MU
SET
    MU.AccountLastUsed = 0
FROM
    Person AS P 
    LEFT JOIN Practitioner AS Pr ON Pr.PersonId = P.PersonId
    LEFT JOIN Client AS C ON C.PersonId = P.PersonId
    LEFT JOIN MembershipUser AS MU ON MU.PractitonerId = Pr.PractitionerId OR ON MU.ClientId = C.ClientId
WHERE
    P.PersonId = @PersonId

有人可以帮我解决这个问题吗,你能用LEFT JOIN进行更新吗?

1 个答案:

答案 0 :(得分:2)

尝试以下查询:

UPDATE MembershipUser
SET   MU.AccountLastUsed = 0
FROM  Person AS P 
    LEFT JOIN Practitioner AS Pr ON Pr.PersonId = P.PersonId
    LEFT JOIN Client AS C ON C.PersonId = P.PersonId
Where 
    P.PersonId = @PersonId
    and (MembershipUser.PractitonerId = Pr.PractitionerId OR MembershipUser.ClientId = C.ClientId)

或者:

UPDATE z    
SET AccountLastUsed = 0
FROM (
    SELECT Mu.Id, Mu.AccountLastUsed
    FROM
        Person AS P 
        LEFT JOIN Practitioner AS Pr ON Pr.PersonId = P.PersonId
        LEFT JOIN Client AS C ON C.PersonId = P.PersonId
        LEFT JOIN MembershipUser AS MU ON MU.PractitonerId = Pr.PractitionerId OR ON MU.ClientId = C.ClientId
    WHERE
        P.PersonId = @PersonId
    )z