SQL Server 2008查询 - 查找不同表中两个不同列中不存在的电子邮件

时间:2012-11-09 23:20:14

标签: sql sql-server-2008-r2

我无法解决这个问题,你能帮助我吗?

我有一张表dbo.Users - >在此表中,我有一个Email列,内部有许多电子邮件

我有另一张桌子dbo.aspnet_Membership - >在此表中,我有Email列,内部有许多电子邮件

我只想提取不在两列中的Emails

例如:

tab1 col1:

111@111.com
222@222.com
333@333.com

tab2 col2:

111@111.com
222@222.com

我想提取(或删除)所有333@333.com电子邮件。

4 个答案:

答案 0 :(得分:4)

因为您使用的是SQL Server 2008,所以可以使用EXCEPT set运算符,如下所示:

SELECT EMAIL FROM Table1
EXCEPT 
SELECT Email FROM table2

SQL Fiddle Demo

更新:这将为您提供Table1中第二个表中不存在的所有电子邮件。但是,如果您想要获取两个表中未显示的所有电子邮件(感谢@gilly3),请尝试以下操作:

(
  SELECT EMAIL FROM Table1
  EXCEPT 
  SELECT Email FROM table2
)
UNION ALL
(
  SELECT EMAIL FROM Table2
  EXCEPT 
  SELECT Email FROM table1
)

Updated SQL Fiddle Demo

答案 1 :(得分:2)

SELECT *
FROM dbo.Users u FULL JOIN dbo.aspnet_Membership m ON u.Email = m.Email
WHERE u.Email IS NULL OR m.Email IS NULL

SQL Fiddle上的演示

答案 2 :(得分:1)

Select *
from dbo.Users
where email not in
(select email
from dbo.aspnet_Membership)

答案 3 :(得分:0)

试试这个

Select * From Users WHERE email NOT IN
(
  Select email From Users u
  JOIN aspnet_Membership m
     ON u.email = m.email
)



Select * From aspnet_Membership WHERE email NOT IN
(
  Select email From Users u
  JOIN aspnet_Membership m
     ON u.email = m.email
)

您可以将select语句更改为DELETE