gpt4 book ai didi

mysql - MySQL类型转换规则

转载 作者:行者123 更新时间:2023-11-29 09:17:15 25 4
gpt4 key购买 nike

我想知道 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 is NULL, except for the NULL-safe <=> equality comparison operator. For NULL <=> NULL, the result is true. 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 or DATETIME 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 to IN() To be safe, always use complete datetime, date, or time strings when doing comparisons. For example, to achieve best results when using BETWEEN with date or time values, use CAST() 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 with BIGINT (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 expression 5.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. The SUM() and AVG() functions return a DECIMAL value for exact-value arguments (integer or DECIMAL), and a DOUBLE value for approximate-value arguments (FLOAT or DOUBLE).

关于mysql - MySQL类型转换规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3744422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com