[英]Left outer join SQL Server
我很困惑為什么這不起作用,我已經多次使用這種類型的語法,但是這個讓我把頭發拉了出來。
我有兩張桌子;
TABLEA
regId name regStatus
1 George 1
2 Jenny 1
3 Penny 1
4 James 1
5 Preston 1
6 Jamie 0
表B
activeRegId passiveRegID Status
1 2 1
1 3 1
1 4 0
6 1 1
我要做的是返回tableA
所有行,不包括那些(tableA.regstatus = 0)
和(tableB.status = 1 for a user regid = 1)
。
我想避免使用NOT IN (select ...)
。
我的查詢到目前為止:
select top 10
tA.regId, tA.name
from
tableA tA
left OUTER JOIN
tableB tB ON tB.activeRegId = tA.regid AND tB.passiveRegID <> 1
AND tB.status <> 1 AND tB.passiveRegID IS NULL
where
tA.regStatus = 1
and tA.regid <> 1
我期待的應該是如下,然而,除了Jamie,我得到了tableA
所有用戶。
regId name
4 James
5 Preston
我認為你需要將一些謂詞從LEFT OUTER JOIN的ON子句中移出,而是將它們作為WHERE子句中的謂詞。
根據您提供的數據,我無法准確確定謂詞應該是什么,但是您在LEFT OUTER JOIN的ON子句中包含的任何謂詞僅用於排除表B中的行, 而不是表A.
使用LEFT OUTER JOIN,您仍將獲得表A的所有記錄,除非它們被WHERE子句中的謂詞排除。
編輯根據評論,我認為這將有效,其中'loggedInUserId'是登錄用戶的表A中的regId:
SELECT top 10
tA.regId,
tA.name
FROM tableA tA1
JOIN tableA tA2
ON (tA1.regId <> tA2.regId
AND tA2.regStatus <> 0)
LEFT OUTER JOIN tableB tB
ON (tA1.regId = tB.activeRegId
AND tA2.regId = tB.passiveRegID
AND tB.Status <> 0)
WHERE tA1.regId = 'loggedInUserId'
AND tB.activeRegId IS NULL
要排除已阻止登錄用戶的人:
SELECT top 10
tA.regId,
tA.name
FROM tableA tA1
JOIN tableA tA2
ON (tA1.regId <> tA2.regId
AND tA2.regStatus <> 0)
LEFT OUTER JOIN tableB tB
ON (
--finding blocked users
(tA1.regId = tB.activeRegId
AND tA2.regId = tB.passiveRegID
AND tB.Status <> 0)
OR
--finding blocking users
(tA2.regId = tB.activeRegId
AND tA1.regId = tB.passiveRegId
AND tB.Status <> 0)
)
WHERE tA1.regId = 'loggedInUserId'
AND tB.activeRegId IS NULL
如果您不想使用NOT IN
,那么使用EXCEPT
排除那些您不想要的東西呢?
SELECT regId
FROM tableA
EXCEPT
SELECT tA.regId
FROM tableA tA
JOIN tableB tB ON (tB.activeRegId = tA.regid AND tB.passiveRegID = 1 AND tB.status = 1)
WHERE tA.regStatus = 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.