权游游牧族:众所周知!一句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进行分组查询
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换成需要显示对应的数字即可。