问题
I created a table in MySQL:
CREATE TABLE index_test(
moment DATETIME,
one_more_attr VARCHAR(10)
);
ALTER TABLE index_test ADD INDEX(moment);
There're two query strings:
A: `SELECT * FROM index_test WHERE moment LIKE '2015-06-08%'`
B: `SELECT * FROM index_test WHERE moment BETWEEN '2015:06:08 00:00:00' AND '2015:06:08 23:00:00'`
Using the 'explain' statement, I found that statement B is using the index, but A not.
And when I make 'moment' varchar, they both use the index. Is anybody can tell me the reason?
回答1:
In MySQL the DATETIME type is stored internally as an 8 byte number, and not as a text string. Therefore, the index you created on the moment column will work for looking up a given numerical date value.
In your query:
SELECT * FROM index_test WHERE moment LIKE '2015-06-08%'
the MySQL engine first implicitly casts the moment column to a VARCHAR type and then does the comparison against '2015-06-08%'.
回答2:
To solve this query:
SELECT * FROM index_test WHERE moment LIKE '2015-06-08%'
MySQL has to convert all datetime values to String in order to make the comparison.
So it cannot use the index.
来源:https://stackoverflow.com/questions/31128241/mysql-datetime-index-is-not-working-while-using-like