使用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)
谢谢!
答案 0 :(得分:2)
这是MySQL如何将text / varchar转换为整数的结果。
select TOP 1 *
from dbo.persons
where LastName like '%Dan%'
ORDER BY LastName ;
为第二列提供select *, cast(b.a as unsigned) from (select "None|679501|3371371|0" as a) b where a=0
。
如果将整数转换为文本,则将按预期获得0行:
0
答案 1 :(得分:2)
结果与您使用的分隔符为|
无关。任何非数字字符都将相同。同样,在这种情况下,null
和None
都不是特殊的。那可以是任何字符串。
在表达式0="0|679501|3371371|0"
中,MySQL正在对该字符串执行“从字符串到整数”的操作,并与0进行比较。它的行为类似于C语言atoi
的工作方式。解析在第一个非数字字符处停止。如果字符串不是以数字字符开头,那么它将产生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。
答案 2 :(得分:0)
这是由于根据操作数coercibilities进行的隐式类型转换。您的第一个查询:
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 automatically converts numbers to strings as necessary, and vice versa.