MySQL 类型转换的坑

一、BUG复现

1. 表字段

字段名类型长度主键非空
idint2TrueTrue
namevarchar255FalseTrue

2. 表记录

idname
0张三
1李四
2王五

3. sql语句

select * from demo where id=0;
Result:
+----+----------+
| id |   name   |
+----+----------+
| 0  |   张三   |
+----+----------+

select * from demo where id='0';
Result:
+----+----------+
| id |   name   |
+----+----------+
| 0  |   张三   |
+----+----------+

select * from demo where id='hhh';
Result:
+----+----------+
| id |   name   |
+----+----------+
| 0  |   张三   |
+----+----------+

select * from demo where id='1';
Result:
+----+----------+
| id |   name   |
+----+----------+
| 1  |   李四   |
+----+----------+

select * from demo where id='1hhh';
Result:
+----+----------+
| id |   name   |
+----+----------+
| 1  |   李四   |
+----+----------+

select * from demo where id='hhh1';
Result:
+----+----------+
| id |   name   |
+----+----------+
| 0  |   张三   |
+----+----------+

二、问题原因

查阅 MySQL 官方文档后发现 文档中有这样一句话:

Comparison operations result in a value of 1 (TRUE), 0 (FALSE), or NULL. These operations work for both numbers and strings. Strings are automatically converted to numbers and numbers to strings as necessary.

意思是在做两个值的比较时,比较运算的结果是1 (TRUE),0 (FALSE)或NULL。这些操作适用于数字和字符串。字符串会自动转换为数字,数字会根据需要转换为字符串。

在 sql语句中,如果字符串开头是数字,则将字符串转化为开头的数字;对于非开头的 sql语句,字符串默认转换为 0

三、解决办法

注意书写格式

既然 MySQL 的类型转换有这么多的坑,那我们在书写 sql语句时首先要明确字段的类型,使用相同类型的数据做判断。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值