sql—在mysql中使用`|`字符作为其值的列进行搜索

83qze16e  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(438)

a 作为表中的列 b ,我想了解为什么搜索会为 a=0 状况!

mysql> select * from (select "0|679501|3371371|0" as a) b where a=0;
+--------------------+
| a                  |
+--------------------+
| 0|679501|3371371|0 |
+--------------------+
1 row in set, 2 warnings (0.00 sec)

mysql> select * from (select "079501|3371371|0" as a) b where a=0;
Empty set, 1 warning (0.04 sec)

mysql> select * from (select "None|679501|3371371|0" as a) b where a=0;
+-----------------------+
| a                     |
+-----------------------+
| None|679501|3371371|0 |
+-----------------------+
1 row in set, 2 warnings (0.00 sec)

mysql> select * from (select "null|679501|3371371|0" as a) b where a=0;
+-----------------------+
| a                     |
+-----------------------+
| null|679501|3371371|0 |
+-----------------------+
1 row in set, 2 warnings (0.00 sec)

mysql> select * from (select "679501|null|3371371|0" as a) b where a=0;
Empty set, 1 warning (0.01 sec)

提前谢谢!

8yoxcaq7

8yoxcaq71#

这是由于根据操作数强制性进行隐式类型转换。您的第一个查询:

select * from (select "0|679501|3371371|0" as a) b where a=0;

返回一行自 0|679501|3371371|0 具有数字字符( 0 )在它的开始,它等于转换比较的另一面,但这是:

select * from (select "9|679501|3371371|0" as a) b where a=0;

返回null。mysql会根据需要自动将数字转换为字符串,反之亦然。

ddarikpa

ddarikpa2#

这是mysql将text/varchar转换为整数的结果。 select *, cast(b.a as unsigned) from (select "None|679501|3371371|0" as a) b where a=0 给予 0 对于第二列。
如果将整数转换为文本,则会得到0行: select * from (select "None|679501|3371371|0" as a) b where a='0'

yshpjwxd

yshpjwxd3#

结果与您使用的分隔符是 | . 对于任何非数字字符都是一样的。同样,两者都不是 null 也不是 None 在这方面是特别的。可以是任何一根弦。
在表达式中, 0="0|679501|3371371|0" ,mysql正在对字符串执行“string to int”并与0进行比较。它的行为和 atoi 在c工作。解析在第一个非数字字符处停止。如果字符串不是以数字字符开头,那么它将生成0。
您可以通过以下查询简化对行为的检查:

> select 0="0|1|2";
+-----------+
| 0="0|1|2" |
+-----------+
|         1 |
+-----------+
1 row in set, 1 warning (0.00 sec)
``` `"0|1|2"` 转换为整数的值为0。解析停止于 `|` . 比较0=0得到1。

select 0="0x1x2";
+-----------+
| 0="0x1x2" |
+-----------+
| 1 |
+-----------+
1 row in set, 1 warning (0.00 sec)
``` "0x1x2" 转换为整数的值为0。解析停止于 | . 比较0=0得到1。

> select 0="1|2|0";
+-----------+
| 0="1|2|0" |
+-----------+
|         0 |
+-----------+
1 row in set, 1 warning (0.00 sec)
``` `"1|2|0"` 转换为整数的值为1。解析停止于 `|` . 比较0=1得到0。

select 1="1x2x0";
+-----------+
| 1="1x2x0" |
+-----------+
| 1 |
+-----------+
1 row in set, 1 warning (0.00 sec)
``` "1x2x0" 转换为整数的值为1。解析停止于 | . 比较1=1得到1。

> select 0="null|1|2";
+--------------+
| 0="null|1|2" |
+--------------+
|            1 |
+--------------+
1 row in set, 1 warning (0.00 sec)
``` `"null|1|2"` 转换为整数的值为0,因为字符串不是以数字开头的,解析将立即停止。默认值为0。比较0=0得到1。

select 0="foo|1|2";
+-------------+
| 0="foo|1|2" |
+-------------+
| 1 |
+-------------+
1 row in set, 1 warning (0.00 sec)
``` "foo|1|2" 转换为整数的值为0,因为字符串不是以数字开头的,解析将立即停止。默认值为0。比较0=0得到1。

相关问题