日期:2014-05-16  浏览次数:20808 次

两个表的对比问题
各位大佬们好,我现在有这样一个问题:
表newMail和表mailAddress.
--------------------
newMail:
ID       mail           Flag
1      kyroc@163.com            NULL
2      yiyoc@126.com            NULL
3      leocha@tom.com          X
4      nancy@163.com            X
-----------------
mailAddress:
ID       mail                Tag
1      lyroct@126.com            NULL
2      nancy@163.com                 NULL
3      kyroc@163.com              NULL
4      xixi@acer.com           X
-----------------
如何才能得到两个表中的所有mail,但不包含重复的mail,单个表中Flag或Tag字段为X的也不包含.
上面两个表中我希望得到的mail为:kyroc@163.com,yiyoc@126.com,lyroct@126.com
我用
SELECT   DISTINCT   `mail`   FROM   `newMail`   where   `Flag`   is   NULL
UNION
SELECT   DISTINCT   `mail`   FROM   `mailAddress`   where   `Tag`   is   NULL
会得到kyroc@163.com,yiyoc@126.com,lyroct@126.com,nancy@163.com,多了个nancy@163.com
请问大佬们怎么修改?谢谢了,我一直在线

------解决方案--------------------
按照LZ的意思只有两个MAIL地址。
kyroc@163.com也是重复。


mysql> select * from newmail;
+----+---------------+------+
| id | mail | flag |
+----+---------------+------+
| 1 | kyroc@163.com | NULL |
| 2 | yiyoc@126.com | NULL |
| 3 | leoha@tom.com | x |
| 4 | nancy@163.com | x |
+----+---------------+------+
4 rows in set (0.00 sec)

mysql> select * from mailaddress;
+----+----------------+------+
| id | mail | tag |
+----+----------------+------+
| 1 | lyroct@126.com | NULL |
| 2 | nancy@163.com | NULL |
| 3 | kyroc@163.com | NULL |
| 4 | xixi@acer.com | 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 |
+----------------+------+
| lyroct@126.com | NULL |
| yiyoc@126.com | 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

结果:
kyroc@163.com,yiyoc@126.com,lyroct@126.com

------解决方案--------------------
看大家这么踊跃,我也来一个。
按照人怎么去做,程序就怎么写的思路,总能写出来的:

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
)