2013-10-31 26 views
1

我有一個需要創建的用戶名列表。我可以查詢表以找出存在的內容,但是如何查詢列表中的項不存在?列出不在where子句中但不在表中的項目

即。

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

但如果只ad存在,哪些SQL我可以用返回bc

回答

1

你可以嘗試這樣的事:

-- 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 

基本上你加入您現有的表,你正在檢查的用戶名,並且僅返回那裏有沒有匹配的結果。

結果:

UserName 
-------- 
b 
c 

(2 row(s) affected) 
+0

謝謝,你的回答我指出了正確的方向。使用這個:(選擇'a'union'b'等)除了(從aspnet_Users中選擇用戶名('a','b','c','d')中的用戶名),如果a和c已經存在返回b和d。編輯:抱歉無法獲取代碼塊的工作 – atamata