Most efficient query to get last modified record in large table

后端 未结 3 1723
说谎
说谎 2021-01-29 04:06

I have a table with a large number of records ( > 300,000). The most relevant fields in the table are:

  • CREATE_DATE
  • MOD_DATE

Those are updat

相关标签:
3条回答
  • 2021-01-29 04:42

    The most efficient way for this query would be to use an index for the column MOD_DATE.

    From How MySQL Uses Indexes

    8.3.1 How MySQL Uses Indexes Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times faster than reading sequentially.

    You can use

    SHOW CREATE TABLE UPDATE_TIME;
    

    to get the CREATE statement and see, if an index on MOD_DATE is defined.

    To add an Index you can use

    CREATE INDEX
    
    CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name
        [index_type]
        ON tbl_name (index_col_name,...)
        [index_option]
        [algorithm_option | lock_option] ...
    

    see http://dev.mysql.com/doc/refman/5.6/en/create-index.html

    0 讨论(0)
  • 2021-01-29 04:46

    Use EXPLAIN:

    http://dev.mysql.com/doc/refman/5.0/en/explain.html

    This tells You how mysql executes statement, thanks to that You can figure out most efficient way, cause it depends on Your db structure and there is no one universal solution.

    0 讨论(0)
  • 2021-01-29 04:58

    Make sure that both of those fields are indexed.

    Then I would just run -

    select max(mod_date) from table
    

    or create_date, whichever one.

    Make sure to create 2 indexes, one on each date field, not a compound index on both.

    As for a discussion of the difference between this and using limit, see MIN/MAX vs ORDER BY and LIMIT

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