先测试一下union运行的特点:
1. select * from union1 union all select * from union2;
结果:
1.如果union1指定返回的列,那union2返回的列数和对应的数据类型要一致,但列名统一用union1的
2.如果union1不指定列,union2可以不指定,但指定了就要和union1中的顺序,列数一致,可以跳过列找一致的数据类型
利用union求两表交集:
1.先用union all求两表并集,交集:两表都有行a,合并之后就有 两个行a,以任意列作为分组条件,那么group by a.column1 having count(*)>1,就得出两表交集
2.使用内连接或等值连接
3.使用in:表1中的id,name,age,在表2中有相同的,那么先用子查询 查出表2中数据,表1再使用in 匹配表2中相同的数据
select t . id , t . name , t . age from table1 t where t . id in (select id from table2 ) and t . name in (select name from table2) and t . age from(...)
总结一下:合并查询再分组 count()>1 、 内连接或等值连接 、 表1各列 in 子查询 and in 子查询...
求差集:
1. not in 子查询
2.合并查询再分组 count()<2
子查询用法:
1.用在select 后面 ,查询结果作为列返回:select u.id , (select school from user where id=u.id) as shl,u.name from user u;
结论:子查询可以用主查询的数据:表名,主查询查出的列。子查询作为列返回,主查询查出的每一行逐一执行子查询
注:这个子查询的源表必须是真实的表
2.用在from后面,先执行该子查询,做为主查询的源表:
select school, count(school) as num from (select school from user) school group by school;
注:聚集函数用在group by分出的每个组,如果没有用group by而用聚集函数,默认查出的结果整个作为一组
注:聚集函数操作每个分组,返回一个结果,如果列中有与聚集参数不同的列,将只取每一个分组的第一行
3.作为where子句