2013-11-24 46 views
2

我有表shopEmail列。T-SQL:[列]不像[從另一個選擇的任何值]

另外我還有另一個表UnsubscribedEmailPattern列。

如何才能選擇只與Email列的商店列不匹配任何EmailPattern值從Unsubscribed表?

例子:

退訂有這些記錄:

aaa 
bbb 
ccc 

我希望像結果:

select * 
from Shop 
where Email not like "%aaa%" 
    and Email not like "%bbb%" 
    and Email not like "%ccc%" 

回答

4
Select * 
From shop 
Where not exists (
    Select 1 
    From unsubscribed 
    Where shop.email like '%' + unsubcribed.emailpattern + '%' 
) 
0

這將工作:

-- setup test tables 
CREATE TABLE #Shop (ID INT, Email VARCHAR(100)); 
CREATE TABLE #Unsubscribed (EmailPattern VARCHAR(100)); 

-- fill with example data 
INSERT #Shop VALUES (1,'[email protected]'); 
INSERT #Shop VALUES (2,'[email protected]'); 
INSERT #Shop VALUES (3,'[email protected]'); 
INSERT #Shop VALUES (4,'[email protected]'); 
-- general phrase 
INSERT #Unsubscribed VALUES ('test'); 
-- specific email 
INSERT #Unsubscribed VALUES ('[email protected]'); 
--INSERT #Unsubscribed VALUES ('@'); -- watch out, this will match every email! 
--INSERT #Unsubscribed VALUES ('_'); -- so will this 

-- filter results: 
-- This returns rows from Table A (Shop), when they do not match anything in table B (Unsubscribed) 
SELECT 
    A.* 
FROM 
    #Shop A 
    LEFT JOIN #Unsubscribed B ON A.Email LIKE '%' + B.EmailPattern + '%' 
WHERE 
    B.EmailPattern IS NULL; 

DROP TABLE #Shop; 
DROP TABLE #Unsubscribed; 

請注意,如果某些短語或字符進入取消訂閱模式,它可能會匹配每個記錄!

+0

請備份你的斷言,它更有效率。您發佈的查詢使用帶有過濾器的左連接運算符; WHERE NOT EXISTS直接使用左反半連接。隨着您向#Shop添加更多行,贊成後者的(輕微)性能差異會增加。在MS-SQL 2008和2012上進行測試。 –

+1

另請參閱:http://www.sqlperformance.com/2012/12/t-sql-queries/left-anti-semi-join –

+0

在本文中有很好的閱讀,感謝鏈接。我不知道這種方法。我的主張已被刪除。 – laylarenee