ORDER BY date and time BEFORE GROUP BY name in mysql

后端 未结 10 558
星月不相逢
星月不相逢 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:28

    Another way to solve this would be with a LEFT JOIN, which could be more efficient. I'll first start with an example that considers only the date field, as probably it is more common to store date + time in one datetime column, and I also want to keep the query simple so it's easier to understand.

    So, with this particular example, if you want to show the oldest record based on the date column, and assuming that your table name is called people you can use the following query:

    SELECT p.* FROM people p
    LEFT JOIN people p2 ON p.name = p2.name AND p.date > p2.date
    WHERE p2.date is NULL
    GROUP BY p.name
    

    What the LEFT JOIN does, is when the p.date column is at its minimum value, there will be no p2.date with a smaller value on the left join and therefore the corresponding p2.date will be NULL. So, by adding WHERE p2.date is NULL, we make sure to show only the records with the oldest date.

    And similarly, if you want to show the newest record instead, you can just change the comparison operator in the LEFT JOIN:

    SELECT p.* FROM people p
    LEFT JOIN people p2 ON p.name = p2.name AND p.date < p2.date
    WHERE p2.date is NULL
    GROUP BY p.name
    

    Now, for this particular example where date+time are separate columns, you would need to add them in some way if you want to query based on the datetime of two columns combined, for example:

    SELECT p.* FROM people p
    LEFT JOIN people p2 ON p.name = p2.name AND p.date + INTERVAL TIME_TO_SEC(p.time) SECOND > p2.date + INTERVAL TIME_TO_SEC(p2.time) SECOND
    WHERE p2.date is NULL
    GROUP BY p.name
    

    You can read more about this (and also see some other ways to accomplish this) on the The Rows Holding the Group-wise Maximum of a Certain Column page.

提交回复
热议问题