我不确定如何正确地提出这个问题,但现在是:
表1
id | email
---------------------------
1 test@test.com
---------------------------
2 random@test.com
---------------------------
3 magic@test.com
---------------------------
4 example@test.com
---------------------------
5 noreply@test.com
---------------------------
6 admin@test.com
---------------------------
7 editor@test.com
表2
id | email_two
---------------------------
7 test@test.com
---------------------------
10 random@test.com
---------------------------
33 magic@test.com
---------------------------
99 example@test.com
---------------------------
109 master@test.com
---------------------------
299 blaster@test.com
问题:
如何正确连接两个表,并通过电子邮件获取不匹配的结果?例如,我需要从两个表中得到的是:
noreply@test.com
admin@test.com
editor@test.com
master@test.com
blaster@test.com
因为其他电子邮件相互匹配。
代码
SELECT email_two FROM table2 b WHERE NOT EXISTS (SELECT * FROM table1 a WHERE a.email = b.email_two
此代码仅返回table2中缺少的代码,但我无法找到在一个查询中从两个表返回缺失结果的正确方法。
感谢您的回答。
答案 0 :(得分:1)
你想要的最合适的操作是FULL OUTER JOIN
,遗憾的是MySQL不支持它。
您可以改为使用UNION ALL
:
SELECT email_two AS email
FROM table2 b
WHERE NOT EXISTS (SELECT * FROM table1 a
WHERE a.email = b.email_two)
UNION ALL
SELECT email
FROM table1 a
WHERE NOT EXISTS (SELECT * FROM table2 b
WHERE a.email = b.email_two)
答案 1 :(得分:1)
您可以使用LEFT JOIN和UNION ALL来获取此信息,下面是可以帮助您获取这些记录的示例查询。
select t1.email as 'email' from t1 LEFT JOIN t2 on t1.email = t2.email
where t2.email is null
UNION ALL
select t2.email as 'email' from t2 LEFT JOIN t1 on t2.email = t1.email
where t1.email is null;