一.分组查询
分组查询的语句:
select 分组函数、字段(必须是group by 后面的字段) (5)
from 表 (1)
where 分组前筛选 (2)
and 筛选条件
group by 分组列表(单个字段,多个字段,函数,表达式,别名)(3)
having 分组后筛选(分组函数,别名) (4)
order by (单个字段,多个字段,函数,表达式,别名) (6)
执行顺序:(1)(2)(3)(4)(5)(6)
group by :函数
例子:每个长度名字的员工个数
select count(*) ,length(last_name)
from employees
group by length(last_name)
group by 表达式:
例子:不同年薪的员工个数
select count(),salary12(1+ifnull(commission_pct,0))
from employees
group by salary*12(1+ifnull(commission_pct,0))
( 在mysql中,group by中可以使用别名;where中不能使用别名;order by中可以使用别名。其余像oracle,hive中别名的使用都是严格遵循sql执行顺序的,group by后面不能用别名。mysql特殊是因为mysql中对查询做了加强。)
group by 别名:
select count(),salary12*(1+ifnull(commission_pct,0)) as 年薪
from employees
group by 年薪
二.连接查询:
查询的字段来自于多个表,就叫做连接查询,又叫多表查询
连接查询的语句:
select 查询列表
from 表1,from表2
等值连接查询的语句:
select 查询列表
from 1 as 别名1,from表2 as 别名2
where 别名1.字段=别名2.字段
and 分组前筛选
and 筛选条件
group by 分组列表
having 分组后筛选
order by 排序列表
非等值连接查询语句:
select 查询列表
from 表1,表2
where 非等值连接条件
and 筛选条件
group by 分组列表
having 分组后筛选
order by 排序列表
自连接查询语句:
select 查询列表
from 表 as 别名1,表 as 别名2
where 别名1.字段=别名2.字段
and 筛选条件
group by 分组列表
having 分组后筛选
order by 排序列表
注:为表起别名的好处:
提高语句的简洁度
区分重名的字段