该篇文章主要是对mysql的查漏补缺,该篇包括:
- 排序和限制
- 聚合
- 表联结
- 子查询与联合
排序和限制
使用关键字 order by和limit;
//排序
select *
from tablename
[where condition]
[order by field1 [desc/asc],field2 [desc/asc],...,fieldn [desc/asc]]说明:
order by后面可以跟多个不同的排序字段,并且每一个排序字段可以有不同的排序顺序;- 如果排序字段的值一样,则相同的字段按照第二个排序字段进行排序。
\\限制查询
select ... [limit offset_start,row_count]说明
- offset_start表示记录起始偏移值,row_count表示要查询的记录行数。默认offset_start=0,所以可以这么写(limit 100,即offset_start=0;row_count=100);
limit经常与order by一起使用进行记录的分页显示;limit属于MySQL扩展SQL92的语法,在其他数据库上并不能通用。
聚合
使用关键字聚合函数(sum/count/max/min等)、group by、with rollup、having等。
select [field1,...,fieldn] fun_name
from tablename
[where where_condition]
[group by field1,...,field2 [with rollup]]
[having where_condition]说明
- fun_name表示聚合函数,如sum(field)/count(1)/max(field)/min(field);
group by表示要进行分类聚合的字段;with rollup,表示对分类聚合的结果进行再汇总;having表示对分类后的结果再进行条件过滤。
举例
例一
# 在用户表上,统计各个部门的人数
select department,count(1)
from users
group by department| department | count(1) |
|---|---|
| 人事部 | 5 |
| 研发部 | 10 |
| 总裁 | 3 |
例二
# 统计各个部门人数,又要统计总人数
select department,count(1)
from users
group by department
with rollup;| department | count(1) |
|---|---|
| 人事部 | 5 |
| 研发部 | 10 |
| 总裁 | 3 |
| null | 18 |
例三
# 统计人数大于5的部门
select department,count(1)
from users
group by department
having count(1)>5;| department | count(1) |
|---|---|
| 研发部 | 10 |
表联结
使用关键词join、left join、right join、on等
select t1.feild1...
from table1 t1 [left/right] join table2 t2
on t1.fieldn = t2.fieldm
where where_condition说明
- 表连接分为
内联结和外联结,他们之间主要区别:内联结仅选择两张表中互相匹配的记录,而外联结会包含其他不匹配的记录; - 外联结分为
左联结和右联结;左联结包含所有左边表中的记录甚至右边表中没有和它匹配的记录,右联结相反。
子查询与联合
使用关键字in/not in、=/!=、exists/not exists、union、union all。
# 子查询形如
select * from table1
where department in(select department
from table2
where where_condition)
#联合
select * from table1
union [all]
select * from table2
...
union [all]
select * from tablen;说明
- 子查询可以转化为表联结;
- 表联结在很多情况下要优于子查询;
- union和union all的主要区别是union all 把结果集直接合并在一起,有可能有重复记录;union 是把union all的结果进行一次distinct,去除重复记录后的结果。