mysql 怎样先排序再分组

权游游牧族:众所周知!一句SqL语句不能先排序再分组。因此这里给出几个案例

--表结构--
create table `shop` (
    `id` int (10) PRIMARY KEY,
    `shop_name` varchar (100),
    `item_name` varchar (100),
    `price` int (10)
); 

insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('1','小卖部','酱油','12');
insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('2','小卖部','醋','15');
insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('3','小卖部','脉动','20');
insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('4','小卖部','沙姜','2');
insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('5','超市','猪肉','24');
insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('6','超市','生菜','6');
insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('7','超市','菜心','5');
insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('8','连锁店','生姜','3');
insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('9','超市','牛肉','30');
insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('10','连锁店','蒜头','2');
insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('11','连锁店','黄瓜','20');

对价格price进行排序而后再根据商店类型shop_name进行分组查询sql

select * from (select * from shop order by price desc) a GROUP BY a.shop_name数据库

结果只是按照表数据的顺序,简单地进行了分组查询操做,可是这时候咱们还不能下结论说这条sql就是错误的,咱们用另外一个数据库版本(MySql 5.5.57)测试一下。测试

最后放上相应的解决办法:

-方法一,仅适用于低于5.7版本的MySql--
select * from (select * from shop order by price desc) a GROUP BY a.shop_name; 

--方法二--
select * from (select * from shop order by price desc limit 999999) a GROUP BY a.shop_name;

--方法三--
select * from shop a where N > (select count(*) from shop b where b.shop_name = a.shop_name and a.price < b.price) order by a.shop_name,a.price desc;

PS:方法二中使用limit,须要limit的范围足够大能包括全部数据,而且每种分类只会显示一条数据,可是数据较多时运行效率要比方法三快上不少,方法三可以控制每种分类显示多少条数据,把N换成须要显示对应的数字便可。.net

阅读原文

相关文章
相关标签/搜索