MYSQL GROUP BY ORDER BY 分組排序獲取第一條數據

mysql 排序語句的寫法,網上真是林林總總,但能用的不多。甚至有很多寫法,從語法上看,就根本沒有排序的樣子。

求人不如求己,自己來吧。

有兩種寫法:

1.根據需要調整正序還是倒序

select * from tabnamexxxx t 
where t.id=(select id from tabnamexxxx t2 where t2.com = t.com order by t2.updatetime desc limit 1)
and t.com in ('xxxx','xxxxx')
GROUP BY t.com ;

2.更加的簡單粗暴,如果是少量的數據,直接單條數據查詢,然後 union all,適合工具一次性查詢,肯定是不適合在項目中用的,會被領導打死的(此爲免責聲明)。

select * from 
 (select  * from tablexxxxxx t where t.com = 'xxxxxx' order by t.updatetime desc limit 1) t 
 
 union all 
 
select * from 
 (select  * from tablexxxxxx t where t.com = 'xxxxxx' order by t.updatetime desc limit 1) t 
 
 union all 
 
select * from 
 (select  * from tablexxxxxx t where t.com = 'xxxxxx' order by t.updatetime desc limit 1) t 
 
 union all 
 
select * from 
 (select  * from tablexxxxxx t where t.com = 'xxxxxx' order by t.updatetime desc limit 1) t ;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章