group by查詢每組時間最新的一條記錄


最近需要查詢每組時間最新的記錄
表如下:
目標結果是:
 
 
一開始的想法:
select * from
 
(select * from log where account_id = 45 order by shop_id,create_time desc)  w
 
group by w.shop_id
 
這種寫法看着沒毛病,但是查詢出來不是每組最新的一條
 
 
正確的寫法很多這里說個認為比較簡單的
select * from log where id in
 
(select SUBSTRING_INDEX(GROUP_CONCAT(id order by create_time desc), ',', 1)   from log where account_id = 45 group by shop_id)
 
分部解讀:
根據條件查詢出分組的所有按時間降序的記錄id並拼接
1.select GROUP_CONCAT(id order by create_time desc) from log where account_id = 45 group by shop_id
 
 
  1. 查詢每個分組中時間最新的那條記錄的id
select SUBSTRING_INDEX(GROUP_CONCAT(id order by create_time desc), ',', 1)   from log where account_id = 45 group by shop_id
 
3.
select * from log where id in
 
(select SUBSTRING_INDEX(GROUP_CONCAT(id order by create_time desc), ',', 1)   from log where account_id = 45 group by shop_id)
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM