Search code examples
phpmysqlsqlgroup-bygreatest-n-per-group

mysql group and order rows


I have following table 'persons' with same persons in different rows

id |   firstname   |   surname   | date_created
------------------------------------------------------
3  | Nelli         | Schaller    | 2017-08-22 20:57:19
------------------------------------------------------
4  | Carl          | Schaller    | 2019-06-21 08:29:45
------------------------------------------------------
48 | Nelli         | Schaller    | 2020-06-25 13:06:09
------------------------------------------------------   
49 | Carl          | Schaller    | 2020-06-25 13:06:09

What I want to get are all unique Schallers with the biggest id / newest date_created value.

I tried this

SELECT id, CONCAT(surname, ", ", firstname) AS person, date_created
FROM persons
WHERE
surname LIKE "schall%"
GROUP by firstname, surname 
ORDER BY date_createdDESC, surname ASC LIMIT 0, 10

but get only as expected the first two entries (id 3 and 4) but I need 48 and 49. As mentioned in some comment in this case the LIKE statement isn't necessary but in real live it will be the source for an autocomplete field so I need the LIKE Any idea how to manage that?


Solution

  • Use NOT EXISTS:

    SELECT p.id, CONCAT(p.surname, ', ', p.firstname) AS person, p.date_created
    FROM persons p
    WHERE p.surname LIKE '%schall%'
    AND NOT EXISTS (SELECT 1 FROM persons WHERE firstname = p.firstname AND surname = p.surname AND id > p.id)
    ORDER BY p.date_created DESC, person
    

    If the condition to pick the latest of each group is the column date_created then change:

    ...AND id > p.id
    

    with

    ...AND date_created > p.date_created