0

我对为什么这不起作用感到困惑,我已经多次使用过这种类型的语法,但这种语法让我把头发拉了出来。

我有两张桌子;

表A

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不包括那些 where(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

我所期待的应该如下,但是,tableA除了 Jamie,我让所有用户都参与进来。

regId name
4     James
5     Preston
4

2 回答 2

1

我认为您需要将一些谓词移出 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
于 2012-12-09T02:25:28.550 回答
1

如果你不想使用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
于 2012-12-09T03:06:27.913 回答