Mysql datetime index is not working while using 'like'

让人想犯罪 __ 提交于 2020-01-30 02:55:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!