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

后端 未结 6 619
既然无缘
既然无缘 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:15

    Try this query -

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

    Then use EXPLAIN to analyze queries.


    SELECT t1.* FROM foo t1
      LEFT JOIN foo t2
        ON t1.id < t2.id AND t1.uid = t2.uid
    WHERE t2.id is NULL;
    

提交回复
热议问题