[轉]Mysql將數據分組後取出時間最近的數據
阿新 • • 發佈:2017-05-26
jpg rom and max函數 mark 地址 sdn net class
但是,我需要創建視圖,Mysql中視圖裏不允許出現查詢子句。求大神些一條SQL語句,能實現既不出現子句,又能查出正確數據。謝謝!
如題,我在網上也找過相關解決方法,很多解答都是這麽一句SQL語句:
select Id,AccountId,Mark,max(CreateTime) as Latest from AccountMark as b group by AccountId
使用Max函數。但是在我查出來的數據中似乎有些不對,如圖,反白的那一條數據,Mark字段和CreateTime字段根本不對應啊!
這是怎麽回事?使用Max函數後在分組這樣靠譜嗎?
還有一條語句:select *,COUNT(AccountId) as Num from
(select * from AccountMark order by CreateTime desc) `temp`
group by AccountId order by CreateTime desc
這樣查出來的數據是對的
但是,我需要創建視圖,Mysql中視圖裏不允許出現查詢子句。求大神些一條SQL語句,能實現既不出現子句,又能查出正確數據。謝謝!
解決方法:
select * from AccountMark as b where not exists(select 1 from AccountMark where AccountId= b.AccountId
and b.CreateTime<CreateTime )
原文地址:http://bbs.csdn.net/topics/390958705
[轉]Mysql將數據分組後取出時間最近的數據