我的问题是一般性问题:
教义对待
$entitity->getTest()->clear();
进入此 sql 查询:
DELETE FROM test WHERE test_id = '6'
-> test_id 是数据库中的一个整数,mysql 会自动转换该值以使其工作。 但正确的查询是:
DELETE FROM test WHERE test_id = 6
我在这里找到了一些讨论:
stackoverflow.com/questions/21762075/mysql-automatically-cast-convert-a-string-to-a-number
code.openark.org/blog/mysql/implicit-casting-you-dont-want-to-see-around
mysql 文档说:
http://dev.mysql.com/doc/refman/5.5/en/type-conversion.html
"The following rules describe how conversion occurs for comparison operations" (..) In all other cases, the arguments are compared as floating-point (real) numbers.
文档还说明了一个问题:
Comparisons that use floating-point numbers (or values that are converted to floating-point numbers) are approximate because such numbers are inexact. This might lead to results that appear inconsistent
那么为什么 doctrine orm 和 dbal 也如此呢?这不是整数表的问题吗?只有bigint?
另请看这里:
http://www.cubrid.org/cubrid_implicit_type_conversion
-> 它表明这不是问题。
所以我的问题是:使用 where int_val = '1' (string) 进行查询没什么大不了的,或者这会很危险。如果这很危险,那么这里的设计问题是加速学说吗?
最佳答案
来自文档:
If one or both arguments are
NULL
, the result of the comparison isNULL
, except for theNULL
-safe<=>
equality comparison operator. ForNULL <=> 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
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.If one of the arguments is a decimal value, comparison depends on the other argument. The arguments are compared as decimal values if the other argument is a decimal or integer value, or as floating-point values if the other argument is a floating-point value.
In all other cases, the arguments are compared as floating-point (real) numbers.
您的案例属于“所有其他案例”。
字符串将被转换为 FLOAT
然后与你的 int_val
进行比较.
如果字符串很好地转换(值如 '1'
、 '0.1'
或 '1E5'
),结果值将与整数进行比较。
如果不是(假设您传递了类似 '1235xxx'
的值),可能的前导数字将被转换为 float (如果没有则为 0
),其余部分将被截断。此外,还会生成警告。
在字符串中传递 id 的原因可能是您的 id 不一定必须是整数。它也可以是字符串或日期。
可能 ORM 有生成 DELETE
的通用代码适用于任何数据类型的查询。
关于php - mysql将字符串自动转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24762038/