How to SELECT by MAX(date)?

前端 未结 12 1542
独厮守ぢ
独厮守ぢ 2020-12-03 02:49

This is the table structure:

CREATE TABLE `reports` (
  `report_id` int(11) NOT NULL auto_increment,
  `computer_id` int(11) NOT NULL default \'0\',
  `date_e         


        
相关标签:
12条回答
  • 2020-12-03 03:22

    Works perfect for me:

    (SELECT content FROM tblopportunitycomments WHERE opportunityid = 1 ORDER BY dateadded DESC LIMIT 1);
    
    0 讨论(0)
  • 2020-12-03 03:22

    Did this on a blog engine to get the latest blog. I adapted it to your table structure.

    SELECT * FROM reports WHERE date_entered = (SELECT max(date_entered) FROM REPORTS)
    
    0 讨论(0)
  • 2020-12-03 03:25

    This would work perfectely, if you are using current timestamp

    SELECT * FROM reports WHERE date_entered = (SELECT max(date_entered) FROM REPORTS)
    

    This would also work, if you are not using current timestamp but you are using date and time column seperately

    SELECT * FROM reports WHERE date_entered = (SELECT max(date_entered) FROM REPORTS) ORDER BY time DESC LIMIT 1
    
    0 讨论(0)
  • 2020-12-03 03:26

    This is a very old question but I came here due to the same issue, so I am leaving this here to help any others.

    I was trying to optimize the query because it was taking over 5 minutes to query the DB due to the amount of data. My query was similar to the accepted answer's query. Pablo's comment pushed me in the right direction and my 5 minute query became 0.016 seconds. So to help any others that are having very long query times try using an uncorrelated subquery.

    The example for the OP would be:

    SELECT 
        a.report_id, 
        a.computer_id, 
        a.date_entered
    FROM reports AS a
        JOIN (
            SELECT report_id, computer_id, MAX(date_entered) as max_date_entered
            FROM reports
            GROUP BY report_id, computer_id
        ) as b
    WHERE a.report_id = b.report_id
        AND a.computer_id = b.computer_id
        AND a.date_entered = b.max_date_entered
    

    Thank you Pablo for the comment. You saved me big time!

    0 讨论(0)
  • 2020-12-03 03:26

    Workaround but working solution

    Only if ID is autoincrement, you can search for the maximum id instead of the max date. So, by the ID you can find all others fields.

    select *
    from table
    where id IN ( 
                  select max(id)
                  from table
                  group by #MY_FIELD#
                  )
    
    0 讨论(0)
  • 2020-12-03 03:28

    This should do it:

    SELECT report_id, computer_id, date_entered
    FROM reports AS a
    WHERE date_entered = (
        SELECT MAX(date_entered)
        FROM reports AS b
        WHERE a.report_id = b.report_id
          AND a.computer_id = b.computer_id
    )
    
    0 讨论(0)
提交回复
热议问题