-
两个要求交集的表(列)的结构要一致,对应的字段数,字段类型都应该相同;将两个数据的数据列用 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
-
内连接inner join。将两个数据列,条件必须涉及需要比较的列,这里没有比较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
-
带IN关键字的查询。需要比较多少列数据是相同的就必须有多少个IN。这个时候一定要控制列,列太多不建议用。
SELECT * FROM student AS a where a.name in (select name from teacher )AND a.ID in (select ID from teacher);
-
带EXISTS关键字的子查询。这个语句说白了也是通过判断teacher中是否有满足两个相等的条件,来得出来的。SELECT * FROM student AS a where EXISTS (select *from teacher b where a.name =b.name AND a.ID=b.ID)