• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

两个表的对比有关问题

mysql 搞代码 7年前 (2018-06-01) 170次浏览 已收录 0个评论

两个表的对比问题
各位大佬们好,我现在有这样一个问题:
表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
)


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:两个表的对比有关问题

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址