2017-04-12 69 views
0

後不匹配的行我不知道如何正確地問這個,但在這裏它是:迴流連接兩個表

表1

id | email 
--------------------------- 
1   [email protected] 
--------------------------- 
2   [email protected] 
--------------------------- 
3   [email protected] 
--------------------------- 
4   [email protected] 
--------------------------- 
5   [email protected] 
--------------------------- 
6   [email protected] 
--------------------------- 
7   [email protected] 

表2

id | email_two 
--------------------------- 
7   [email protected] 
--------------------------- 
10  [email protected] 
--------------------------- 
33  [email protected] 
--------------------------- 
99  [email protected] 
--------------------------- 
109  [email protected] 
--------------------------- 
299  [email protected] 

問題:

如何正確連接兩個表,並通過電子郵件獲得不匹配的結果?例如,我需要從兩個表中獲得的是:

[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 

因爲其他電子郵件相互匹配。

代碼

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

此代碼只返回從表2失蹤的人,但我不能找到一個正確的方法,從兩個表在一個查詢返回結果失蹤。

感謝您的任何答案。

回答

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) 
+0

謝謝。這是工作。 – Tauras

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;