为什么在MySQL中比较类型不会引发错误?

如果您尝试将字符串与int进行比较,MySQL不会引发错误,因为它将字符串转换为int。让我们首先创建一个表-

mysql> create table DemoTable1852
     (
     Value1 varchar(20),
     Value2 int
     );

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable1852 values('1John',1);
mysql> insert into DemoTable1852 values('John',1);
mysql> insert into DemoTable1852 values('1',1);
mysql> insert into DemoTable1852 values('John1',1);

使用select语句显示表中的所有记录-

mysql> select * from DemoTable1852;

这将产生以下输出-

+--------+--------+
| Value1 | Value2 |
+--------+--------+
| 1John  |      1 |
| John   |      1 |
| 1      |      1 |
| John1  |      1 |
+--------+--------+
4 rows in set (0.00 sec)

这是比较MySQL中类型的查询,它不会引发错误-

mysql> select Value1,Value2, Value1=Value2 as Result from DemoTable1852;

这将产生以下输出-

+--------+--------+--------+
| Value1 | Value2 | Result |
+--------+--------+--------+
| 1John  |      1 |      1 |
| John   |      1 |      0 |
| 1      |      1 |      1 |
| John1  |      1 |      0 |
+--------+--------+--------+
4 rows in set, 3 warnings (0.00 sec)