Creating an index on a timestamp to optimize query

前端 未结 4 658
别跟我提以往
别跟我提以往 2020-12-13 03:41

I have a query of the following form:

SELECT * FROM MyTable WHERE Timestamp > [SomeTime] AND Timestamp < [SomeOtherTime]

I would like

4条回答
  •  一生所求
    2020-12-13 04:16

    If your queries are mainly using this timestamp, you could test this design (enlarging the Primary Key with the timestamp as first part):

    CREATE TABLE perf (
      , ts INT NOT NULL
      , oldPK 
      , ... other columns 
    , PRIMARY KEY(ts, oldPK)
    , UNIQUE (oldPK)
    ) ENGINE=InnoDB ;
    

    This will ensure that the queries like the one you posted will be using the clustered (primary) key.

    Disadvantage is that your Inserts will be a bit slower. Also, If you have other indices on the table, they will be using a bit more space (as they will include the 4-bytes wider primary key).

    The biggest advantage of such a clustered index is that queries with big range scans, e.g. queries that have to read large parts of the table or the whole table will find the related rows sequentially and in the wanted order (BY timestamp), which will also be useful if you want to group by day or week or month or year.

    The old PK can still be used to identify rows by keeping a UNIQUE constraint on it.


    You may also want to have a look at TokuDB, a MySQL (and open source) variant that allows multiple clustered indices.

提交回复
热议问题