mysql查询两个表的交集方法:
1、两个要求交集的表(列)的结构要一致,对应的字段数,字段类型都应该相同;将两个数据的数据列用 union all 关键字合并;将上面的所有需要比较的列 group by ;最后 having count(任意一列,不能多列)>1,那么就是交集。
select a.* from( select * from teacher union all select * from student)a group by a.id,a.name,a.sex having count(a.sex)>1
2、内连接或者等值连接。jion(inner jion)。将两个数据列,条件必须涉及需要比较的列,这里没有比较sex列,所以比2步多了一行数据。
select * from student as a join teacher as b on a.name =b.name and a.id=b.id或者select * from student as a inner join teacher as b on a.name =b.name and a.id=b.id
3、带in关键字的查询。需要比较多少列数据是相同的就必须有多少个in。这个时候一定要控制列,列太多不建议用。
select * from student as a where a.name in (select name from teacher )and a.id in (select id from teacher);
4、带exists关键字的子查询。这个语句说白了也是通过判断teacher中是否有满足两个相等的条件,来得出来的。
select * from student as a where exists (select *from teacher b where a.name =b.name and a.id=b.id)
更多相关免费学习推荐:mysql教程(视频)
以上就是mysql怎么查两个表的交集的详细内容。
