我想知道 mysql 类型转换的规则是什么。例如
如果foo
列是 int,select foo/2 from table
似乎会产生小数。如果 foo
是 float ,select sum(foo) from table
会将 sum(foo) 列返回为 double 值。 select i*i from table
如果 i 是 int,则给出 bigint。
使用 +-/* 等常用运算符或 sum/avg 等聚合时,这里的类型转换规则是什么?
最佳答案
类型转换的规则非常简单。引用自 MySQL Manual :: Type Conversion in Expression Evaluation :
When an operator is used with operands of different types, type conversion occurs to make the operands compatible. Some conversions occur implicitly.
The following rules describe how conversion occurs for comparison operations:
If one or both arguments are
NULL
, the result of the comparison isNULL
, except for theNULL
-safe<=>
equality comparison operator. ForNULL <=> NULL
, the result istrue
. No conversion is needed.If both arguments in a comparison operation are strings, they are compared as strings.
If both arguments are integers, they are compared as integers.
Hexadecimal values are treated as binary strings if not compared to a number.
If one of the arguments is a
TIMESTAMP
orDATETIME
column and the other argument is a constant, the constant is converted to a timestamp before the comparison is performed. This is done to be more ODBC-friendly. Note that this is not done for the arguments toIN()
To be safe, always use complete datetime, date, or time strings when doing comparisons. For example, to achieve best results when usingBETWEEN
with date or time values, useCAST()
to explicitly convert the values to the desired data type.In all other cases, the arguments are compared as floating-point (real) numbers.
对于算术运算符,结果根据以下规则确定。引用自 MySQL Manual :: Arithmetic Operators
In the case of
-
,+
, and*
, the result is calculated withBIGINT
(64-bit) precision if both arguments are integers.If one of the arguments is an unsigned integer, and the other argument is also an integer, the result is an unsigned integer.
If any of the operands of a
+
,-
,/
,*
,%
is a real or string value, the precision of the result is the precision of the argument with the maximum precision.In division performed with
/
, the scale of the result when using two exact values is the scale of the first argument plus the value of the div_precision_increment system variable (which is 4 by default). For example, the result of the expression5.05 / 0.014
has a scale of six decimal places(360.714286)
.
对于聚合函数,以下内容适用。引用自 MySQL Manual :: Aggregate Functions :
For numeric arguments, the variance and standard deviation functions return a
DOUBLE
value. TheSUM()
andAVG()
functions return aDECIMAL
value for exact-value arguments (integer orDECIMAL
), and aDOUBLE
value for approximate-value arguments (FLOAT
orDOUBLE
).
关于mysql - MySQL类型转换规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3744422/