1

我有一个需要创建的用户名列表。我可以查询表以找出存在哪些项目,但如何查询我的列表中的哪些项目不存在?

IE。

select username from aspnet_Users where UserName in (a,b,c,d, etc)

但如果只有aandd存在,我可以使用什么 SQL 来返回band c

4

1 回答 1

1

You could try something like this:

-- Included a CTE here just so this example is runnable; 
-- You don't need it in your query
WITH aspnet_Users (UserName) AS
(
    SELECT 'a' UNION
    SELECT 'd'
)
SELECT
    n.UserName
FROM
    aspnet_Users e
RIGHT JOIN 
    (VALUES ('b'), ('c')) AS n(UserName)
    ON 
    e.UserName = n.UserName

Basically you join your existing table to the usernames you're checking, and only return the results where there was no match.

Results:

UserName
--------
b
c

(2 row(s) affected)
于 2013-10-31T12:30:27.770 回答