Using ORDER BY and GROUP BY together

前端 未结 7 1959
清酒与你
清酒与你 2020-11-28 05:30

My table looks like this (and I\'m using MySQL):

m_id | v_id | timestamp
------------------------
6    |   1  | 1333635317
34   |   1  | 1333635323
34   |            


        
7条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 05:39

    One way to do this that correctly uses group by:

    select l.* 
    from table l
    inner join (
      select 
        m_id, max(timestamp) as latest 
      from table 
      group by m_id
    ) r
      on l.timestamp = r.latest and l.m_id = r.m_id
    order by timestamp desc
    

    How this works:

    • selects the latest timestamp for each distinct m_id in the subquery
    • only selects rows from table that match a row from the subquery (this operation -- where a join is performed, but no columns are selected from the second table, it's just used as a filter -- is known as a "semijoin" in case you were curious)
    • orders the rows

提交回复
热议问题