目录
何为高级查询
-
高级查询分为统计查询、分组查询、关联查询(联表查询/多表查询)和子查询,子查询下节课讲。
统计查询
- 通过聚合函数来实现;
- 常见的聚合函数
- sum:求和
- max:求最大值
- min:求最小值
- count:统计数据条数
3.语法
selcet 聚合函数(字段) from fuser;
分组查询
关键字:
group by 条件:通过指定的条件进行分组;
having:对分组后的数据进行筛选;
select * from fuser;
select sex, count(*) from fuser GROUP BY sex;
select sum(age) from fuser ;
select address, count(*) from fuser GROUP BY address;
where和having的区别:
-
执行时机不同:where是分组之前进行过滤,不满足where条件,不参与分组;而having是分组 之后对结果进行过滤。
-
判断条件不同:where不能对聚合函数进行判断,而having可以。
-
注意事项:
-
分组之后,查询的字段一般为聚合函数和分组字段,查询其他字段无任何意义;
-
执行顺序: where > 聚合函数 > having;
-
支持多字段分组, 具体语法为 : group by columnA,columnB。
-
关联查询
内连接
例:
select * from fuser f,tb_score s where f.sid=s.sid;
select * from fuser f inner join tb_score s on f.sid=s.sid;
select * from fuser f join tb_score s where f.sid=s.sid;
select * from fuser f join tb_score s on f.sid=s.sid;
外连接
左连接:
select * from fuser f left join tb_score s on f.sid=s.sid;
select * from fuser f left outer join tb_score s on f.sid=s.sid;
右连接:
select * from fuser f right join tb_score s on f.sid=s.sid;
select * from fuser f right outer join tb_score s on f.sid=s.sid;
全连接
全连接的查询结果是左外连接和右外连接查询结果的并集,即使一些记录关联不上,也能够把部分信息查询出来。
例:
(select * from fuser f left join tb_score s on f.sid = s.sid)
union
(select * from tb_score s right join fuser f on f.sid = s.sid)
表之间数据的导入
把某张表的结构数据导入到一张新表里面:create table 新表 select 字段 from 旧表 where 成立的条件;
把某张表的结构导入到一张新表里面:create table 新表 select 字段 from 旧表 where 不成立的条件