如何避免MySQL的隐式转换(截断错误的DOUBLE值)

当我执行此查询时

mysql> SELECT * FROM test WHERE sample_col = 'foo';

用这张桌子.

mysql> SHOW CREATE TABLE test\G
*************************** 1. row ***************************
       Table: test
Create Table: CREATE TABLE `test` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `sample_col` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

mysql> SELECT * FROM test;
+----+------------+
| id | sample_col |
+----+------------+
|  1 |          0 |
|  2 |          1 |
|  3 |          2 |
+----+------------+
3 rows in set (0.00 sec)

MySQL自动将WHERE子句的’foo’转换为零,我收到了此警告消息.

mysql> SELECT * FROM test WHERE sample_col = 'foo';
+----+------------+
| id | sample_col |
+----+------------+
|  1 |          0 |
+----+------------+
1 row in set, 1 warning (0.00 sec)

mysql> SHOW WARNINGS;
+---------+------+-----------------------------------------+
| Level   | Code | Message                                 |
+---------+------+-----------------------------------------+
| Warning | 1292 | Truncated incorrect DOUBLE value: 'foo' |
+---------+------+-----------------------------------------+
1 row in set (0.00 sec)

如何配置MySQL以将此警告报告为错误? (或者如何停止隐式转换?)

我已将SQL_MODE设置为严格但似乎不会影响SELECT语句.

mysql> SELECT @@SQL_MODE;
+------------------------------------------+
| @@SQL_MODE                               |
+------------------------------------------+
| STRICT_ALL_TABLES,NO_ENGINE_SUBSTITUTION |
+------------------------------------------+

MySQL的版本是5.6.16.

mysql> SELECT @@VERSION;
+------------+
| @@VERSION  |
+------------+
| 5.6.16-log |
+------------+

[UPDATE]

查询SELECT * FROM test WHERE sample_col =’foo’;是我的代码的错误.由于隐式转换,我无法注意到这个错误.
我的目的是“如何避免此类查询”或“如何快速检测此错误”.所以我想知道停止隐式转换的方法或者将此错误级别从警告更改为错误的方法.

最佳答案 您应该尝试使用CAST或CONVERT函数显式地强制转换它,如下所示,并且不要指望隐式转换.

SELECT * FROM test WHERE sample_col = cast('foo' as int);

(OR)

SELECT * FROM test WHERE cast(sample_col as varchar) = 'foo';

此外,没有必要将INT类型列与字符串值和AFAIK进行比较,没有这样的设置来阻止隐式转换.如果你真的想导致错误而不是将其转换为0然后明确地转换它;在这种情况下,它会出错.

有关更多信息,请参见Type Conversion in Expression Evaluation.

点赞