21

我有以下表格:

Users
Banned

SELECT u.*
FROM Users
WHERE u.isActive = 1
    AND
      u.status <> 'disabled'

我不想包含用户也可能在 Banned 表中的任何行。

最好的方法是什么?

我可以这样做在 where 子句中放置一个子查询,这样它就可以执行以下操作:

u.status <> 'disabled' and not exist (SELECT 1 FORM Banned where userId = @userId)

我认为最好的方法是进行 LEFT JOIN,我该怎么做?

4

4 回答 4

30

根据这个答案,在 SQL-Server 中使用NOT EXISTSLEFT JOIN/IS NULL

SELECT  *
FROM    Users u
WHERE   u.IsActive = 1
AND     u.Status <> 'disabled'
AND     NOT EXISTS (SELECT 1 FROM Banned b WHERE b.UserID = u.UserID)

编辑

为了完整起见,这就是我将如何使用 a LEFT JOIN

SELECT  *
FROM    Users u
        LEFT JOIN Banned b
            ON b.UserID = u.UserID
WHERE   u.IsActive = 1
AND     u.Status <> 'disabled'
AND     b.UserID IS NULL        -- EXCLUDE ROWS WITH A MATCH IN `BANNED`
于 2012-10-29T20:06:33.963 回答
8

您只需检查LEFT JOIN使用 Banned 获得的值是否为NULL

SELECT U.*
FROM Users U
    LEFT JOIN Banned B ON B.userId = U.userId
WHERE U.isActive = 1
    AND U.status <> 'disabled'
    AND B.userId IS NULL -- no match in the Banned table.
于 2012-10-29T19:57:19.920 回答
5
select u.*
from Users u
left outer join Banned b on u.userId = b.userId
where u.isActive = 1
    and u.status <> 'disabled'
    and b.UserID is null
于 2012-10-29T19:56:40.423 回答
-1
SELECT u.*
FROM Users u
LEFT JOIN Banned b ON u.userId = b.userId AND b.userRoles = 'VIP'
WHERE u.isActive = 1 AND b.id IS NULL

如果您需要结果并且应该排除某些内容并且它不是表的键 ID,请使用它。

于 2015-05-07T11:11:04.630 回答