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

后端 未结 6 587
既然无缘
既然无缘 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;
    
    0 讨论(0)
  • 2020-11-27 07:11

    This code works on me:

    SELECT * FROM foo GROUP BY foo.uid 
    HAVING MAX(foo.id)
    
    0 讨论(0)
  • 2020-11-27 07:14

    This has worked for me thanks!

    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;
    

    my version:

    SELECT * FROM messages t1 JOIN (SELECT MAX(id) id FROM messages  where uid = 8279 and actv=1 GROUP BY uid ) t2 ON t1.id = t2.id ORDER BY datex desc LIMIT 0,10;
    

    this code below doesn't return all rows I want because if max id column is an inactive one then it skips the group even if the group has active rows..

    select * from messages where uid = 8279 and actv=1 and id In (Select max(id) From messages Group By uid) order by datex desc;
    
    0 讨论(0)
  • 2020-11-27 07:14

    The easiest way : you can select from selected list that is sorted.

    SELECT * FROM (SELECT * FROM foo order by id DESC) AS footbl
    group by uid
    order by id DESC
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-11-27 07:21

    Returning the last row of each GROUP BY in MySQL with WHERE clause:

    SELECT *
    FROM foo
    WHERE id IN (
      SELECT Max(id)
      FROM foo
      WHERE value='XYZ'
      GROUP BY u_id
    )
    LIMIT 0,30
    
    0 讨论(0)
提交回复
热议问题