1、where语句优化
select m.cid,u.id from order m join customer u on( m.cid =u.id )where m.dt='20200808';
可优化为
select m.cid,u.id from (select * from order where dt='20200808') m join customer u on( m.cid =u.id);
2、union优化
尽量不要使用union (union 去掉重复的记录)而是使用 union all 然后在用group by 去重
3、count distinct优化
不要使用count (distinct cloumn) ,而要使用子查询实现count(distinct)
select count(1) from (select id from tablename group by id) tmp;
4、用in代替join
如果需要根据一张表的字段约束另一个张表,用in代替join,in比join快
select id,name from tb1 a join tb2 b on(a.id = b.id);
可优化为
select id,name from tb1 where id in(select id from tb2);
5、消灭子查询内的 group by
消灭子查询内的 group by 、 COUNT(DISTINCT),MAX,MIN。 可以减少job的数量。
6、count
count(*):所有行进行统计,包括NULL行
count(1):所有行进行统计,包括NULL行
count(column):对column中非Null进行统计
7、sql扩展
select
count(*) as nums
from (
select
a.*,b.*
from a join b on a.id = b.id
where...
) t
where t.city = "beijing"
group by t.sex
having t.sex is not null
order by nums desc
limit n;
--需求:统计来自于北京男女各有多少人(性别为空的排除)并且按照人数的倒数进行排序。
--重点:
--select确定之后 立马去寻找from关键字 因为from后面跟的就是操作的表。
--表可能是真实存在的表 如果是真实的表 直接操作使用
--表也可能不存在 设法通过查询把这个表变出来 基于这个虚拟的表再进行操作
--只有表确定之后 在结合业务确定查询返回的字段或者表达式
--嵌套子查询,先执行里面的查询语句 后执行外部的查询语句
4万+

被折叠的 条评论
为什么被折叠?



