如何判断mysql中数据表中两个列之间的相同记录和不同记录
2010-05-30 12:00
609 查看
问题的描述如下:给定数据库中的两列,每个列内的所有记录可以视为一个集合,如何求这两个集合的交集,差集等。示例:
两个列的交集是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 having count(*) > 1;
两个列的交集的补集:
SELECT name
FROM (SELECT firstname as name FROM table1 union SELECT username as name FROM table2) as alltable
group by name having count(*) = 1;
第一个列和第二个列的差集:
SELECT * FROM table1
WHERE firstname not in
(SELECT name
FROM (SELECT firstname as name FROM table1 union SELECT username as name FROM table2) as alltable
group by name having count(*) > 1)
类似的可以求第二个列和第一个列的差集。如果一个集合是另一个集合的子集,情况会简单一点。如果希望包含重复的记录,使用union all.
大家可以自己考虑一下。当然这个肯定不是唯一的解决方法了,就算抛砖引玉了。
关于union,可以参考http://www.w3schools.com/sql/sql_union.asp
参考:http://www.mysqltutorial.org/compare-two-tables-to-find-unmatched-records-mysql.aspx
table1中字段firstname tom kevin john steven marry anthony | table2中字段username jack tom william tom marry Thomas |
SELECT name
FROM (SELECT firstname as name FROM table1 union SELECT username as name FROM table2) as alltable
group by name having count(*) > 1;
两个列的交集的补集:
SELECT name
FROM (SELECT firstname as name FROM table1 union SELECT username as name FROM table2) as alltable
group by name having count(*) = 1;
第一个列和第二个列的差集:
SELECT * FROM table1
WHERE firstname not in
(SELECT name
FROM (SELECT firstname as name FROM table1 union SELECT username as name FROM table2) as alltable
group by name having count(*) > 1)
类似的可以求第二个列和第一个列的差集。如果一个集合是另一个集合的子集,情况会简单一点。如果希望包含重复的记录,使用union all.
大家可以自己考虑一下。当然这个肯定不是唯一的解决方法了,就算抛砖引玉了。
关于union,可以参考http://www.w3schools.com/sql/sql_union.asp
参考:http://www.mysqltutorial.org/compare-two-tables-to-find-unmatched-records-mysql.aspx
相关文章推荐
- mysql两个表结构相同,如何找出它们的不同记录方法[left join].
- mysql如何去除两个字段数据相同的记录?
- 两个不同数据库之间的两个表如何关联起来查询数据
- MySQL如何查询两个日期之间的记录,编译出错!
- MySQL如何查询两个日期之间的记录
- MySQL如何查询两个日期之间的记录
- Mysql 如何查询两个时间段之间的数据?
- MySQL如何查询两个日期之间的记录
- MySQL如何查询两个日期之间的记录
- MySQL如何查询两个日期之间的记录
- 100分!!!如何实现两个不同手机不同APP之间的实时的数据传递
- MySQL如何查询两个日期之间的记录
- 两个不同数据库之间的两个表如何关联起来查询数据
- 两个不同数据库之间的两个表如何关联起来查询数据
- 截取两个字符串之间不同的部分 sql脚本(可以延伸到进一步判断两字符串之间的相同部分)
- MYSQL生成两个日期之间的所有日期数据
- ios delegate代理,多个/不同/两个view之间传递数据,传递批量数据,多个数据
- mysql中根据一个字段相同记录写递增序号,如序号结果,如何实现?
- 如何判断两个Long类型数据是否相等
- mysql中如何判断 一个数据表是否已经存在