mysql如何进行多类型比较?

How does mysql do multi-type comparison?

我正在做一个项目,由于误解,我们最终将存储的 int 与 MySql 数据库中的字符串进行了比较。我 运行 进行了一些测试,它似乎有效,但我想知道 MySql 如何比较不同的数据类型。

它能把一个转换成另一个吗?如果是,它会同时转换为字符串还是整数?

当您在整数上下文中使用字符串时,例如在算术表达式或与整数的比较中,MySQL 将该字符串的数值作为 DOUBLE 数据类型。

https://dev.mysql.com/doc/refman/5.7/en/type-conversion.html

示范:

mysql> create table foo as select 1+'1' as x;

mysql> show create table foo\G
CREATE TABLE `foo` (
  `x` double NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1

字符串的数值是任何前导数字字符或构成浮点数的其他字符的数值,如-+.e

例如'123abc'的数值为123。

支持科学计数法。

mysql> select 1 + '5e-2xyz' as n;
+------+
| n    |
+------+
| 1.05 |
+------+

如果没有前导字符构成数值,则字符串的数值为0。

Mysql 手册有一个完整的部分专门用于此,称为 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. For example, MySQL automatically converts numbers to strings as necessary, and vice versa.

如果将 int 与字符串进行比较,则两个值都会转换为浮点数并进行比较。