mysql判断两列相等_如何判断mysql中数据表中两个列之间的
相同记录和不同记录...
问题的描述如下:给定数据库中的两列,每个列内的所有记录可以视为⼀个集合,如何求这两个集合的交集,差集等。⽰例:
table1中字段firstnamemysql交集查询
tom
kevin
john
steven
marry
anthony
table2中字段username
jack
tom
william
tom
marry
Thomas
两个列的交集是tom, marry。解决的⽅法是采⽤union和group by:
SELECT name
FROM (SELECT firstname as name FROM table1 union SELECT username as name FROM table2) as alltable
group by name havingcount(*) > 1;
两个列的交集的补集:
SELECT name
FROM (SELECT firstname as name FROM table1 unionSELECT username as name FROM table2) as alltable
group by name havingcount(*) = 1;
第⼀个列和第⼆个列的差集:
SELECT * FROM table1
WHERE firstname not in
(SELECT name
FROM (SELECT firstname as name FROM table1 unionSELECT username as name FROM table2) as alltable
group by name havingcount(*) > 1)
类似的可以求第⼆个列和第⼀个列的差集。如果⼀个集合是另⼀个集合的⼦集,情况会简单⼀点。如
果希望包含重复的记录,使⽤union all.
⼤家可以⾃⼰考虑⼀下。当然这个肯定不是唯⼀的解决⽅法了,就算抛砖引⽟了。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论