Why is using an INT to select a Varchar index containing numbers much slower than using Strings?

早过忘川 提交于 2019-12-04 11:07:54

As stated in the manual:

For comparisons of a string column with a number, MySQL cannot use an index on the column to look up the value quickly. If str_col is an indexed string column, the index cannot be used when performing the lookup in the following statement:

SELECT * FROM tbl_name WHERE str_col=1;

The reason for this is that there are many different strings that may convert to the value 1, such as '1', ' 1', or '1a'.

If necessary, you can always CAST your integer to a string in order to take advantage of the index:

SELECT * FROM example WHERE stuff = CAST(200 AS CHAR);

Warning: MySQL may also skip an index if its character set does not match, even if both values are CHAR. If the following query does not work:

SELECT * FROM example WHERE stuff = CAST(200 AS CHAR);

Then, get your database character set by running show variables like 'character_set_database'; and use that in a CONVERT statement as follows (this example assumes your database character set is latin1 -- replace that with your value of character_set_database):

SELECT * FROM example WHERE stuff = CONVERT(200 USING latin1);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!