前言
在使用group by和order by的時(shí)候,通常并不會(huì)出現(xiàn)什么問題,然而有一種情況會(huì)讓人忽視。那就是對group組內(nèi)數(shù)據(jù)進(jìn)行order的時(shí)候。
通常大家在使用group by和order by的時(shí)候,潛意識(shí)里會(huì)覺得如果group分組里有多條記錄,order by會(huì)對組內(nèi)數(shù)據(jù)進(jìn)行排序,然后group的數(shù)據(jù)會(huì)是order得到的第一條數(shù)據(jù)。實(shí)際上,order對于group的組內(nèi)數(shù)據(jù)并不能進(jìn)行排序!
eg:
CREATE TABLE `tb` (
`id` int(11) NOT NULL ,
`group_id` int(11) NOT NULL ,
`app_id` int(11) NOT NULL ,
`name` varchar(255) NOT NULL ,
PRIMARY KEY (`id`)
);
在表tb中存有不同分組的多個(gè)APPID信息,現(xiàn)在要求查詢每個(gè)分組中最大的那一條APPID的記錄
方案一:select * from tb group by group_id order by app_id desc;
結(jié)果:這種方案實(shí)際上獲取的是物理塊讀取的第一條數(shù)據(jù),并不一定是最大的APPID
方案二:select * from (select * from tb order by group_id DESC,appid DESC) as tmp group by group_id;
結(jié)果:如預(yù)期得到需求的數(shù)據(jù)。