T-SQL:如何select值列表中不在表中的值?

我有一个电子邮件地址列表,其中一些在我的表中,其中一些不是。 我想从列表中select所有的电子邮件,以及它们是否在表格中。

我可以得到邮件地址在这个表中的用户:
SELECT u.* FROM USERS u WHERE u.EMAIL IN ('email1', 'email2', 'email3')

但是,我怎样才能select列表中不存在的值?

而且,我怎么能这样select:

 E-Mail | Status email1 | Exist email2 | Exist email3 | Not Exist email4 | Exist 

提前致谢。

对于SQL Server 2008

 SELECT email, CASE WHEN EXISTS(SELECT * FROM Users U WHERE E.email = U.email) THEN 'Exist' ELSE 'Not Exist' END AS [Status] FROM (VALUES('email1'), ('email2'), ('email3'), ('email4')) E(email) 

对于以前的版本,你可以用一个派生表UNION ALL做一些类似于常量的事情。

 /*The SELECT list is the same as previously*/ FROM ( SELECT 'email1' UNION ALL SELECT 'email2' UNION ALL SELECT 'email3' UNION ALL SELECT 'email4' ) E(email) 

你需要以某种方式创build一个这些值的表,然后使用NOT IN 。 这可以通过临时表,CTE(公用表expression式)或Table Values Constructor (在SQL-Server 2008中可用)完成:

 SELECT email FROM ( VALUES ('email1') , ('email2') , ('email3') ) AS Checking (email) WHERE email NOT IN ( SELECT email FROM Users ) 

第二个结果可以用LEFT JOINEXISTS子查询find:

 SELECT email , CASE WHEN EXISTS ( SELECT * FROM Users u WHERE u.email = Checking.email ) THEN 'Exists' ELSE 'Not exists' END AS status FROM ( VALUES ('email1') , ('email2') , ('email3') ) AS Checking (email) 

如果您不想在数据库中的列表中包含电子邮件,则可以执行以下操作:

 select u.name , u.EMAIL , a.emailadres , case when a.emailadres is null then 'Not exists' else 'Exists' end as 'Existence' from users u left join ( select 'email1' as emailadres union all select 'email2' union all select 'email3') a on a.emailadres = u.EMAIL) 

这样你会得到一个像这样的结果

 name | email | emailadres | existence -----|--------|------------|---------- NULL | NULL | a@b.com | Not exists Jan | j@j.nl | j@j.nl | Exists 

在这种情况下使用IN或EXISTS运算符比左连接更重。

祝你好运 :)

你应该有一个表格,列出要检查的电子邮件。 然后做这个查询:

 SELECT E.Email, CASE WHEN U.Email IS NULL THEN 'Not Exists' ELSE 'Exists' END Status FROM EmailsToCheck E LEFT JOIN (SELECT DISTINCT Email FROM Users) U ON E.Email = U.Email 

这应该适用于所有的SQL版本。

 SELECT E.AccessCode , CASE WHEN C.AccessCode IS NOT NULL THEN 'Exist' ELSE 'Not Exist' END AS [Status] FROM ( SELECT '60552' AS AccessCode UNION ALL SELECT '80630' UNION ALL SELECT '1611' UNION ALL SELECT '0000' ) AS E LEFT OUTER JOIN dbo.Credentials C ON E.AccessCode = c.AccessCode 

使用这个: – SQL Server 2008或更高版本

 SELECT U.* FROM USERS AS U Inner Join ( SELECT EMail, [Status] FROM ( Values ('email1', 'Exist'), ('email2', 'Exist'), ('email3', 'Not Exist'), ('email4', 'Exist') )AS TempTableName (EMail, [Status]) Where TempTableName.EMail IN ('email1','email2','email3') ) As TMP ON U.EMail = TMP.EMail