赞
踩
隐式转换发生的情景:
查询参数类型与数据库字段类型不一致时存在隐式转换
隐式转换的一些规则:
首先从官网获得的隐式转换发生的描述:
The following rules describe how conversion occurs for comparison operations:
NULL
, the result of the comparison is NULL
, except for the NULL
-safe <=> equality comparison operator. For NULL <=> NULL
, the result is true. No conversion is needed.A single-row subquery from a table or tables is not considered a constant. For example, if a subquery returns an integer to be compared to a DATETIME value, the comparison is done as two integers. The integer is not converted to a temporal value. To compare the operands as DATETIME values, use CAST() to explicitly convert the subquery value to DATETIME.
综上,根据上面对文档的理解,隐式转换可以归纳出如下规则:
varchar类型隐式转换的问题
遗留待处理的问题:“数据类型的转换从varchar类型变成了float或者double(猜想应该是float,隐式转换的细节需要另外再去求证)“
回顾一下当时的场景:Round()函数内部是一个varchar类型字段与decimal类型做运算,导致结果变成了一个float
这种情况适用于“所有其他情况下,两个参数都会被转换为浮点数再进行比较“这类情况。官方文档中确实也是这么描述的“a comparison of string and numeric operands takes place as a comparison of floating-point numbers“
隐式转换可能存在的隐患
如下面这个案例,string类型的str_col列上如有和整型常数的比较的where条件就会导致本来str_col上的索引失效。
因为索引是按照string本身来排列的,但是比较中会先进行转换且多种string可能转换成同一个结果,转换完后再进行比较,转换结果不适用原有的基于str_col的索引排序。
发生这个问题的原因是,多种原始值肯会通过隐式转换变成同一个结果,例如字符串的隐式转换中,如果字符串以数字开头且全部都是数字,则转换为数字结果是整个字符串;字符串部分是数字,则转换为数字结果是截止到第一个不是数字的字符为止。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。