基于其他表

时间:2015-11-10 04:49:12

标签: sql sql-server tsql stored-procedures

如图所示,我有四张桌子。只有TableBTableBChild具有外键关系。

我想在这里实现的是确定是否 TableBChild.MemberID匹配TableA.memberNo,其中TableB.isgood为真

如果不是条件不满足,则批量更新isvalid为false。

但我无法将TableBChild.MemberIDMember.MemberNo进行比较。

Update TableB
Set IsValid = 0
From TableA as A
INNER JOIN TableB as B ON A.TableBNo = B.TableBNo And IsGood = 1
INNER JOIN TableBChild as BC ON B.TableBID = BC.TableBID
                             AND BC.MEMBERID != SELECT MemberID 
                                                FROM Member 
                                                WHERE MemberNo = A.MemberNo // This line is not working

enter image description here

3 个答案:

答案 0 :(得分:2)

尝试使用NOT IN代替!=,如下所示:

Update TableB
Set IsValid = 0
From TableA as A INNER JOIN TableB as B
                      ON A.TableBNo = B.TableBNo And IsGood = 1
                 INNER JOIN TableBChild as BC
                       ON B.TableBID = BC.TableBID
AND BC.MEMBERID NOT IN ( SELECT MemberID from Member Where MemberNo = A.MemberNo )

答案 1 :(得分:0)

更改你的最后一行:

AND BC.MEMBERID != (SELECT MemberID from Member Where MemberNo = A.MemberNo)

答案 2 :(得分:0)

我会做什么:

UPDATE TableB
SET IsValid = 0
WHERE TableBID NOT IN 
(
-- this will select TableBID's satisfying:
-- TableB.IsGood is true, 
-- and corresponding TableBChild has memberID that exists in TableA.MemberNo
SELECT tbc.TableBID
FROM TableBChild tbc
INNER JOIN TableB tb ON tb.TableBID = tbc.TableBID
INNER JOIN TableA ta ON tbc.MemberID = ta.MemberNo
WHERE tb.IsGood = 1
)