MySQL query, MAX() + GROUP BY

后端 未结 7 755
不思量自难忘°
不思量自难忘° 2020-11-27 05:16

Daft SQL question. I have a table like so (\'pid\' is auto-increment primary col)

CREATE TABLE theTable (
    `pid` INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
          


        
相关标签:
7条回答
  • 2020-11-27 06:09

    I created an index on rid and timestamp.

    SELECT test.pid, test.cost, test.timestamp, test.rid
    FROM theTable AS test
    LEFT JOIN theTable maxt 
    ON maxt.rid = test.rid
    AND maxt.timestamp > test.timestamp
    WHERE maxt.rid IS NULL 
    

    Showing rows 0 - 2 (3 total, Query took 0.0104 sec)

    This method will select all the desired values from theTable (test), left joining itself (maxt) on all timestamps higher than the one on test with the same rid. When the timestamp is already the highest one on test there are no matches on maxt - which is what we are looking for - values on maxt become NULL. Now we use the WHERE clause maxt.rid IS NULL or any other column on maxt.

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