记MySQL的一次查询经历

今天在MySQL查数据,sql语句如下:
SELECT * FROM `admins` where dep_ids = 24;
发现查出来的数据是包含所有 24 的 dep_ids,我想查的是 dep_ids 只为 24 的数据。
看了一下 dep_ids 的类型,是varchar,并不是int,于是sql改为:
SELECT * FROM `admins` where dep_ids = '24';
这次查出来的数据是正确的。
 
为什么第一次查询,查询条件没加引号也可以查出结果呢,这是因为发生了类型转换例如,MySQL会根据需要自动将字符串转换为数字,反之亦然。
MySQL官方文档(章节12.2 Type Conversion in Expression Evaluation)提到:
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:
为了比较字符串列和数字,MySQL不能使用列上的索引来快速查找值。如果 str_col是索引字符串列,则在以下语句中执行查找时,不能使用索引:
 
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'.
这是因为,有许多不同的字符串可以转换为1,例如 '1',' 1'或 '1a'。
由此可知,在上述的第一次查询中,dep_ids是字符串类型,当输入 int 类型的 24 时,'24,78'、'24,56'都会转换成24,所以会查出 3 条记录。
 
还是MySQL官方文档,给出了将字符串转换为数字以进行比较操作的例子
mysql> SELECT 1 > '6x'; 
-> 0
mysql> SELECT 7 > '6x'; 
-> 1
mysql> SELECT 0 > 'x6'; 
-> 0
mysql> SELECT 0 = 'x6'; 
-> 1
当字符串与整数型值比较时:
如果字符串以数字开头,则截取字符串的前端数字部分转换为整数型,即'6x'的值是 6,'24,56'的值是 24;
如果字符串字符串开头,则该字符串转为整数型的 0,即'x6'的值是0,'北京'的值是0。
 
总结:当查询条件为“字符串字段=数字”时,MySQL会先将字段的值转为 int 类型,再与给出的条件值进行比较。

猜你喜欢

转载自www.cnblogs.com/sunshineliulu/p/10527583.html