DQL:数据查询语言
执行顺序:from-->where-->group by -->(select处的聚合函数)--> having -->select -->distinct-->order by -->limit;
目录
1. 表连接
1.1 内连接
取两张表的交集部分数据,左右两张表的连接字段均有的数据:
#显式内连接
select * from 表a join 表b on 表a.字段=表b.字段;
#隐式内连接
select * from 表a , 表b where 表a.字段=表b.字段;
1.2 左外连接
以左表作为主表的连接,显示左表所有数据,显示右表其(左表有的连接字段)的数据:
select * from a left join b on a.字段=b.字段;
1.3 右外连接
以右表作为主表的连接,显示右表所有数据,显示左表其(右表有的连接字段)的数据:
select * from a right join b on a.字段=b.字段;
1.4 全外连接
显示左、右两张表连接后的所有数据,不存在的显示为NULL
由于现MySQL不支持outer join 查询,因此需要左+右连接来实现全外连接
select * from (
select * from a left join b on a.条件=b.条件
union
select * from a right join b on a.条件=b.条件
);
拓展:
在连接条件on处不仅可以写等条件连接(=),还可以不等值的条件连接(>,<,<>)【大于,小于,不等于】
2. 子查询
2.1 单表的子查询
#放在select后的子查询
select *,(select '固定值') col from 表a where 条件;
#放在where后,当作表使用的子查询
select * from (select * from a)t where 条件;
#放在where条件后的子查询
select * from a where 字段1 in (select 字段1 from b where 条件);
#放在having后的子查询
select 字段1,聚合函数 from a where 条件 group by 字段1 having 字段1 in (select 字段1 from b);
2.2 group by 和 having
group by 指对数据进行分组,在select 查询的字段中只能是 group by 后的字段,和所有表中字段的聚合函数。
where 是先条件筛选再group by 分组,且where条件中不可以有聚合函数做比较运算;
having 跟在group by 的后面,先group by 分组再having筛选。
2.3 聚合函数
常用的聚合函数有:
组内求和:sum()
组内平均:avg()
组内最小值:min()
组内最大值:max()
组内次数统计:count()