Returning the 'last' row of each 'group by' in MySQL

后端 未结 6 623
既然无缘
既然无缘 2020-11-27 06:34

Is there a more efficient way of doing the following?

select * 
    from foo as a
    where a.id = (select max(id) from foo where uid = a.uid group by uid)
          


        
6条回答
  •  孤街浪徒
    2020-11-27 07:11

    if table is big in size. Make view containing all last row id

    create view lastrecords as (select max(id) from foo where uid = a.uid group by uid)
    

    Now join your main query with this view. It will be faster.

      SELECT t1.* FROM tablename as t1
        JOIN lastrecords as  t2
        ON t1.id = t2.id AND t1.uid = t2.uid;
    

    OR You can do join with last records direct in query also:

    SELECT t1.* FROM tablename as t1
    JOIN (SELECT uid, MAX(id) id FROM tablename GROUP BY id) as  t2
    ON t1.id = t2.id AND t1.uid = t2.uid;
    

提交回复
热议问题