limit分页查询
select * from user limit 3;
1是指表中的起始的偏移量(offset),3指实际搜索表中内容的个数
select * from user limit 1,3;
select * from user limit 1 offset 1;
select * from user where sex='M' limit 1,3;
常用写法
select * from user where id>上一页最后一条数据的id值 limit 20;
其中id为当前表的主键,提升limit分页查询的效率,优化在imit的偏移量(offset)的搜索
explain查看SQL语句的执行计划
实际执行属于整表搜索
explain select * from user where sex='M';
实际执行属于条件搜索,遇到满足条件即停止搜索,可提高SQL搜索效率
explain select * from user where sex='M' limit 1;
排序order by
select id,nickname,name,age,sex from user where sex='M' and age>=20 and age<=25 order by age asc;
select id,nickname,name,age,sex from user where sex='M' and age>=20 and age<=25 order by age desc;
<1>使用任何字段来作为排序的条件,从而返回排序后的查询结果。可设定多个字段来排序。
<2>使用 ASC 或 DESC 关键字来设置查询结果是按升序或降序排列。 默认情况下,按升序排列。
<3>添加 WHERE...LIKE 子句来设置条件。
分组group by
select sex from user group by sex;
select count(id),sex from user group by sex;
select count(id),age from user group by age having age>20;
select count(id) as person from user group by sex order by person desc;
<1>group by语句根据一个或多个列对结果集进行分组。
<2>在分组的列上我们可以使用 COUNT, SUM, AVG,等函数。
<3>可使用as对聚合函数得到的值起别名,参与之后的排序操作。
<4>分组之后可以使用having添加选择条件,或者在选择分组时,使用where添加选择条件,推荐使用where处理,若where后面字段存在索引,可以使用索引,提升SQL执行效率。
使用 coalesce 来设置一个可以取代 NUll 的名称,coalesce 语法:
select coalesce(a,b,c);
其中,若a==null,则选择b;如果b==null,则选择c;如果a!=null,则选择a;如果a b c 都为null ,则返回为null(没意义)。