Die*_*oDD 14 mysql string comparison
我正在做一些MySQL测试查询,并意识到将字符串列与0(作为数字)进行比较给出了TRUE!
select 'string' = 0 as res; -- res = 1 (true), UNexpected! why!??!?!
Run Code Online (Sandbox Code Playgroud)
但是,将它与任何其他数字进行比较,正数或负数,整数或小数,false按预期给出(当然除非字符串是数字表示为字符串)
select 'string' = -12 as res; -- res = 0 (false), expected
select 'string' = 3131.7 as res; -- res = 0 (false), expected
select '-12' = -12 as res; -- res = 1 (true), expected
Run Code Online (Sandbox Code Playgroud)
当然,将字符串与'0'字符串进行比较,如预期的那样给出false.
select 'string' = '0' as res; -- res = 0 (false), expected
Run Code Online (Sandbox Code Playgroud)
但为什么它会成真'string' = 0呢?
这是为什么?
fth*_*lla 22
MySQL自动将字符串转换为数字:
SELECT '1string' = 0 AS res; -- res = 0 (false)
SELECT '1string' = 1 AS res; -- res = 1 (true)
SELECT '0string' = 0 AS res; -- res = 1 (true)
Run Code Online (Sandbox Code Playgroud)
并且一个不以数字开头的字符串被计算为0:
SELECT 'string' = 0 AS res; -- res = 1 (true)
Run Code Online (Sandbox Code Playgroud)
当然,当我们尝试将字符串与另一个字符串进行比较时,没有转换:
SELECT '0string' = 'string' AS res; -- res = 0 (false)
Run Code Online (Sandbox Code Playgroud)
但我们可以使用例如+运算符强制转换:
SELECT '0string' + 0 = 'string' AS res; -- res = 1 (true)
Run Code Online (Sandbox Code Playgroud)
最后一个查询返回TRUE,因为我们将字符串'0string'与数字0相加,所以字符串必须转换为数字,SELECT 0 + 0 = 'string'然后再将字符串'string'转换为数字,然后再与0进行比较,然后变成SELECT 0 = 0哪个是真的.
这也有效:
SELECT '1abc' + '2ef' AS total; -- total = 1+2 = 3
Run Code Online (Sandbox Code Playgroud)
并将返回转换为数字的字符串的总和(在这种情况下为1 + 2).
| 归档时间: |
|
| 查看次数: |
4916 次 |
| 最近记录: |