ITPub博客

首页 > 数据库 > MySQL > mysql 字符串和数字比,字符串会隐式转换为数字0

mysql 字符串和数字比,字符串会隐式转换为数字0

原创 MySQL 作者:czxin788 时间:2022-07-15 14:55:47 0 删除 编辑

在mysql中,字符串和数字比,字符串会被转成数字0。

下面我演示:

mysql> create table t (a int primary key, b int,c int, d int, index idx_b_c_d (b,c,d));
Query OK, 0 rows affected (0.14 sec)
mysql> insert into t values (0,0,0,0),(1,1,1,1),(2,2,2,2),(3,3,3,3);
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0
mysql> select  * from t;
+---+------+------+------+
| a | b    | c    | d    |
+---+------+------+------+
| 0 |    0 |    0 |    0 |
| 1 |    1 |    1 |    1 |
| 2 |    2 |    2 |    2 |
| 3 |    3 |    3 |    3 |
+---+------+------+------+
4 rows in set (0.00 sec)

下面演示奇怪现象:

mysql> select  * from t where a=1;
+---+------+------+------+
| a | b    | c    | d    |
+---+------+------+------+
| 1 |    1 |    1 |    1 |
+---+------+------+------+
1 row in set (0.00 sec)
mysql> select  * from t where a='t';
+---+------+------+------+
| a | b    | c    | d    |
+---+------+------+------+
| 0 |    0 |    0 |    0 |
+---+------+------+------+
1 row in set, 1 warning (0.00 sec)
mysql> select  * from t where a='ttt';
+---+------+------+------+
| a | b    | c    | d    |
+---+------+------+------+
| 0 |    0 |    0 |    0 |
+---+------+------+------+
1 row in set, 1 warning (0.00 sec)
mysql> select  * from t where a='bbb';
+---+------+------+------+
| a | b    | c    | d    |
+---+------+------+------+
| 0 |    0 |    0 |    0 |
+---+------+------+------+
1 row in set, 1 warning (0.00 sec)

可以看到,where a='bbb' 能查出a=0的行,这就是因为mysql把字符串bbb转成了数字0。

通过下面可以验证,1表示为真,0表示为假:

mysql> select  'ttt'=0;
+---------+
| 'ttt'=0 |
+---------+
|       1 |
+---------+
1 row in set, 1 warning (0.01 sec)
mysql> select  'ttt'=1;
+---------+
| 'ttt'=1 |
+---------+
|       0 |
+---------+
1 row in set, 1 warning (0.00 sec)
mysql> select  'bbb'=1;
+---------+
| 'bbb'=1 |
+---------+
|       0 |
+---------+
1 row in set, 1 warning (0.00 sec)


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/28916011/viewspace-2905961/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2014-06-03

  • 博文量
    233
  • 访问量
    858430