ORDER BY date and time BEFORE GROUP BY name in mysql

后端 未结 10 515
星月不相逢
星月不相逢 2020-12-01 06:20

i have a table like this:

name    date         time
tom | 2011-07-04 | 01:09:52
tom | 2011-07-04 | 01:09:52
mad | 2011-07-04 | 02:10:53
mad | 2009-06-03 | 00         


        
相关标签:
10条回答
  • 2020-12-01 06:44

    This worked for me:

    SELECT *
    FROM your_table
    WHERE id IN (
        SELECT MAX(id)
        FROM your_table
        GROUP BY name
    );
    
    0 讨论(0)
  • 2020-12-01 06:46

    In Oracle, This work for me

    SELECT name, min(date), min(time)
        FROM table_name
    GROUP BY name
    
    0 讨论(0)
  • 2020-12-01 06:47

    As I am not allowed to comment on user1908688's answer, here a hint for MariaDB users:

    SELECT *
    FROM (
         SELECT *
         ORDER BY date ASC, time ASC
         LIMIT 18446744073709551615
         ) AS sub
    GROUP BY sub.name
    

    https://mariadb.com/kb/en/mariadb/why-is-order-by-in-a-from-subquery-ignored/

    0 讨论(0)
  • 2020-12-01 06:48

    Another method:

    SELECT * 
    FROM (
        SELECT * FROM table_name
        ORDER BY date ASC, time ASC 
    ) AS sub
    GROUP BY name
    

    GROUP BY groups on the first matching result it hits. If that first matching hit happens to be the one you want then everything should work as expected.

    I prefer this method as the subquery makes logical sense rather than peppering it with other conditions.

    0 讨论(0)
提交回复
热议问题