简体   繁体   English

连接两个表后返回不匹配的行

[英]Return not matching rows after joining two tables

I am not sure how to ask this correctly, but here it is: 我不确定如何正确地问这个问题,但是这里是:

table1 表格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

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

Question: 题:

How to correctly join two tables, and get not matching results by email? 如何正确连接两个表,并通过电子邮件获取不匹配的结果? For example, what i need to get from both tables is: 例如,我需要从两个表中得到的是:

noreply@test.com
admin@test.com
editor@test.com
master@test.com
blaster@test.com

because other emails matching each other. 因为其他电子邮件相互匹配。

Code

SELECT email_two FROM table2 b WHERE NOT EXISTS (SELECT * FROM table1 a WHERE a.email = b.email_two

This code returns only missing ones from table2, but i cant find a correct way to return missing results from two tables in one query. 这段代码仅返回table2中缺少的结果,但是我找不到在一个查询中从两个表中返回缺失结果的正确方法。

Thanks for any answers. 感谢您的任何答案。

The most suitable operation for what you want is a FULL OUTER JOIN which is unfortunately not supported in MySQL. 最理想的操作是FULL OUTER JOIN ,不幸的是,MySQL不支持FULL OUTER JOIN

You can use UNION ALL instead: 您可以改用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)

you can use LEFT JOIN and UNION ALL to get this, below is sample query that may help you to get these records. 您可以使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM