group by和order by
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)