sql语句执行顺序之group by、order by
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql语句执行顺序之group by、order by相关的知识,希望对你有一定的参考价值。
参考技术A 1、先执行group by后执行order by,如果相同id的记录只获取id大的一条记录,使用子查询(先排序后分组):select * from (select * from table1 order by id desc limit 9999) a group by type_id;
PS:group by需要和limit配合使用,不使用limit语句会自动被优化掉group by无效。
2、字段值为0的记录不分组,字段值大于0的记录进行分组:
方法1:使用union all
SELECT * FROM `table1` WHERE name='0' UNION ALL SELECT * FROM `table1` WHERE name!='0' group by name;
方法2:使用case when :select的时候判断id是否等于0,等于0的话则赋值,然后再使用group by分组
select * from (select o.add_time,og.id,(CASE WHEN og.product_id<1 THEN o.add_time ELSE og.product_id END) as product_id from order as o left join order_goods as og on o.order_id=og.order_id order by o.add_time desc limit 9999) table1 group by product_id order by add_time desc
拓展:(使用上面sql)如果product_id不为空,需要加上判断只获取开启展示状态的product数据:
select * from (select o.add_time,og.id,(CASE WHEN og.product_id>1 THEN (select id from product where product.id=og.product_id and product.is_show=1) ELSE o.add_time END) as product_id from order as o left join order_goods as og on o.order_id=og.order_id order by o.add_time desc limit 9999) table1 where product_id is not null group by product_id order by add_time desc
方法3:使用isfull()函数 ,思路和方法2一样,都是判断字段值是否为空,若是空值先赋一个临时值后分组
需要注意的是,isfull只能用于判断是否为null,若值是0无效(见图3 图4)
sql语句select group by order by where一般先后顺序
写的顺序:select ... from... where.... group by... having... order by..
执行顺序:from... where...group by... having.... select ... order by...
执行顺序:from... where...group by... having.... select ... order by...
Mysql
全值匹配我最爱,最左前缀要遵守;
带头大哥不能死,中间兄弟不能断;
索引列上少计算,范围之后全失效;
LIKE百分写最右,覆盖索引不写星;
不等空值还有or,索引失效要少用。
以上是关于sql语句执行顺序之group by、order by的主要内容,如果未能解决你的问题,请参考以下文章
sql语句select group by order by where一般先后顺序
sql语句select group by order by where一般先后顺序
查询语句中select from where group by having order by的执行顺序
SQL语句中,如果有group by 和order by两个语句,是先分组还是先排序?