查询的分组与汇总
聚合函数
数量
1.select count(*)from 表名;
2.select count(0)from 表名;
3.select count(字段名)from 表名;
求和
select sum(字段名)from 表名;
平均值
select avg(字段名)from 表名;
最大值和最小值
select max(字段名),min(字段名) from 表名;
分组查询
select prof,sum(字段名),avg(字段名),count(字段名)
from 表名
group by 字段名;
select prof,sum(字段名),avg(字段名)
from 表名
group by字段名
having avg(字段名) >= 1000;
select prof,sum(字段名),avg(字段名)
from 表名
where 字段名 like "%a%"
group by 字段名
having avg(字段名) >= 1000;
创建多表连接查询
为表取别名(as可省略)
表名(可写函数) as 表别名
select st.class_num
-> from teacher as t
-> inner join school_teaching st
-> on t.no=st.teacher_no
-> where t.name="Daniel";
为字段取别名(as可省略)
字段名(可写函数) as 字段别名
1.select prof, sum(sal) as salsum,avg(comm) as 平均
from teacher
group by prof;
2.select prof, sum(sal) salsum,avg(comm) 平均
from teacher
group by prof;
交叉连接
select * from 表名1 cross join 表名2;
内连接
select * from 表名1 inner join 表名2 on 表名1.表1字段名=表名2.表2字段名;
左连接
select * from 表名1 left join 表名2 on 表名1.表1字段名=表名2.表2字段名;
右连接
select * from 表名1 right join 表名2 on 表名1.表1字段名=表名2.表2字段名;
查看Daniel老师的授课的课程表
子查询
子查询 in
select * from 表名 where 条件 字段 in (查询语句);
子查询 exists
select * from 表名 where 条件 exists (查询语句);
子查询 any
select * from 表名 where 条件 字段 > any (查询语句);
子查询 all
select * from 表名 where 条件 字段 > all (查询语句);