Search code examples
mysqlsqlgreatest-n-per-group

How do I change the order before MySQL grouping?


If there is more than 1 identical number in the table, I only bring one. But before bringing it, the first added date comes from the records. I want the last added record to come.

Here is an example;

SELECT * FROM comments WHERE phone_number='01234'

Output:

id | phone | created_at
-----------------------
1   01234   2020-10-27
2   01234   2020-10-28

MySQL code;

SELECT * FROM comments GROUP BY phone_number ORDER BY created_at DESC

MySQL output;

id | phone | created_at
-----------------------
1   01234   2020-10-27

Solution

  • If you want the most recent row, you don't want aggregation. Instead, filter for it:

    select c.*
    from c
    where c.created_at = (select max(c2.created_at)
                          from comments c2
                          where c2.phone = c.phone
                         );
    

    Or use window functions:

    select c.*
    from (select c.*,
                 row_number() over (partition by phone order by created_at desc) as seqnum
          from comments c
         ) c
    where seqnum = 1;
    

    Or, if you want this just for one phone, then you can use order by and limit:

    select c.*
    from c
    where phone = '3244003390'
    order by c.created_at desc
    limit 1;