我有一个需要创建的用户名列表。我可以查询表以找出存在哪些项目,但如何查询我的列表中的哪些项目不存在?
IE。
select username from aspnet_Users where UserName in (a,b,c,d, etc)
但如果只有a
andd
存在,我可以使用什么 SQL 来返回b
and c
?
我有一个需要创建的用户名列表。我可以查询表以找出存在哪些项目,但如何查询我的列表中的哪些项目不存在?
IE。
select username from aspnet_Users where UserName in (a,b,c,d, etc)
但如果只有a
andd
存在,我可以使用什么 SQL 来返回b
and c
?
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)