两个表的对比问题
各位大佬们好,我现在有这样一个问题:
表newMail和表mailAddress.
--------------------
newMail:
ID mail Flag
1 [email protected] NULL
2 [email protected] NULL
3 [email protected] X
4 [email protected] X
—————–
mailAddress:
ID mail Tag
1 [email protected] NULL
2 [email protected] NULL
3 [email protected] NULL
4 [email protected] X
—————–
如何才能得到两个表中的所有mail,但不包含重复的mail,单个表中Flag或Tag字段为X的也不包含.
上面两个表中我希望得到的mail为:[email protected],[email protected],[email protected]
我用
SELECT DISTINCT `mail` FROM `newMail` where `Flag` is NULL
UNION
SELECT DISTINCT `mail` FROM `mailAddress` where `Tag` is NULL
会得到[email protected],[email protected],[email protected],[email protected],多了个[email protected]
请问大佬们怎么修改?谢谢了,我一直在线
——解决方案——————–
按照LZ的意思只有两个MAIL地址。
[email protected]也是重复。
mysql> select * from newmail;
+—-+—————+——+
| id | mail | flag |
+—-+—————+——+
| 1 | [email protected] | NULL |
| 2 | [email protected] | NULL |
| 3 | [email protected] | x |
| 4 | [email protected] | x |
+—-+—————+——+
4 rows in set (0.00 sec)
mysql> select * from mailaddress;
+—-+—————-+——+
| id | mail | tag |
+—-+—————-+——+
| 1 | [email protected] | NULL |
| 2 | [email protected] | NULL |
| 3 | [email protected] | NULL |
| 4 | [email protected] | x |
+—-+—————-+——+
4 rows in set (0.00 sec)
mysql> select mail,flag from (select mail,flag from newmail union all select mai
l,tag from mailaddress) t group by mail
-> having count(mail) = 1 and flag is null;
+—————-+——+
| mail | flag |
+—————-+——+
| [email protected] | NULL |
| [email protected] | NULL |
+—————-+——+
2 rows in set (0.00 sec)
——解决方案——————–
这样得出来的结果才是楼主要要的结果:
select email,tag, count(email) from
(select email,tag from a
union all
select email,flag from b)
t group by email
having count(email)> =1 and tag is null
结果:
[email protected],[email protected],[email protected]
——解决方案——————–
看大家这么踊跃,我也来一个。
按照人怎么去做,程序就怎么写的思路,总能写出来的:
SELECT *
FROM (
SELECT mail
FROM newmail
WHERE flag IS NULL
UNION
SELECT mail
FROM mailaddress
WHERE tag IS NULL
)a
WHERE NOT
EXISTS (
SELECT *
FROM (
SELECT mail
FROM newmail
WHERE flag = "x "
UNION
SELECT mail
FROM mailaddress
WHERE tag = "x "
)b
WHERE a.mail = b.mail
)