开发者

How can I select the latest of three value types in a MySQL database?

开发者 https://www.devze.com 2023-01-18 19:53 出处:网络
Here is an example table: IDtimedatatype 00100xyz0 10200xyz1 20300xyz1 30400xyz2 40200xyz0 50500xyz2 60300xyz0

Here is an example table:

ID  time   data   type  
0   0100   xyz    0  
1   0200   xyz    1  
2   0300   xyz    1  
3   0400   xyz    2  
4   0200   xyz    0  
5   0500   xyz    2  
6   0300   xyz    0  

Data is added based on timestamp so that the last of each type has the latest time stamp.

I would like the result of a SELECT to be:

ID  time   data   type  
5   0500   xyz    2  
2   0300   xyz    1  
6   0300   xyz    0  

And so the last of each 'type' is returned.

I can accomplish the above using three SELECT statements as follows:

SELECT time, data, type FROM table WHERE type=0 ORDER BY time DESC LIMIT 1
SELECT time, data, type FROM table WHERE type=1 ORDER BY time DESC LIMIT 1
SELECT time, data, type FROM table WHERE type=2 OR开发者_如何学GoDER BY time DESC LIMIT 1

Is there a way to combine the above three SELECT statements into one?

Any help appreciated.

Chris


select m.ID, m.time, m.data, m.type
from (
    select type, max(time) as MaxTime
    from MyTable
    group by type
) mm
inner join MyTable on mm.type = m.type 
    and mm.MaxTime = m.time
0

精彩评论

暂无评论...
验证码 换一张
取 消