How to index the mysql time field

when querying, you need to query the scope according to the time field, timestamp type. Statement does not have subqueries, associated queries, only look up this table.
it takes about 4.5 seconds to find 50, 000 results. This field has been indexed, but the type of explain is still ALL.
how to optimize?

The

statement is between and. It takes about the same time to change the > = and < = queries.

SELECT id,name,sex,city,headimg FROM user WHERE starttime >="2018-05-15" AND starttime <= "2018-07-27 23:59:59" ORDER BY starttime DESC 

look at the amount of data in your table, if many, tens of thousands of levels, even if the time is indexed, it will be very slow.
in some cases, due to the large amount of data, mysql believes that full table scanning is fast and not suitable for indexes.

your sql can be optimized:

SELECT
    b.id,
    b.NAME,
    b.sex,
    b.city,
    b.headimg
FROM (SELECT
    id 
FROM
    USER
WHERE
    starttime >= '2018-05-15'
AND starttime <= '2018-07-27 23:59:59'
ORDER BY
    starttime DESC) a   inner join USER b on b.id = a.id; 

Don't return a lot of data at one time. If there is a lot of data, get it multiple times. In fact, mysql processes sql queries very quickly. Time is mainly spent on initiating connections or sending back data (50, 000 pieces of data are very large) , which gives you the impression that sql execution is so slow.


whether the laxative
index is used has something to do with the percentage of data in the index range retrieved in the entire table. If you search for a long period of time, in most cases more than 20 will scan
, so you can use force index to see how to retrieve it faster. Choose
as needed, and the other is upstairs @ helloworld, but the internal sorting after mysql5.7 is invalid. So you need to put the order by on the outer
last point. The long execution time may also be caused by the sorting of 5W pieces of data. If starttime and the primary key id are in the same order, you can remove the order by clause


can you post your sql statement, and what is the index of your timestamp?


it doesn't matter how much you find out. What matters is how much data you have. Then you add the index, and if it is only the simplest sql statement, you first make sure that your index is valid and whether you use the index.


SELECT id,name,sex,city,headimg FROM user WHERE starttime > = unix_timestamp ('2018-05-15') AND starttime < = unix_timestamp ('2018-07-27') ORDER BY starttime DESC

)
Menu