Why is the result of `select 'a'=0;` 1?

前端 未结 4 1454
刺人心
刺人心 2020-12-21 15:25
mysql> SELECT \'a\'=\'b\'=\'c\';
+-------------+
| \'a\'=\'b\'=\'c\' |
+-------------+
|           1 |
+-------------+
mysql> select \'a\'=0, \'b\'=\'c\';
+---         


        
4条回答
  •  温柔的废话
    2020-12-21 15:45

    When you compare a string literal with a numeric value, MySQL must to convert the string literal to a numeric value as well so that the comparison can take place. Since 'a' is not a number, the resulting value is zero—hence the equality. When comparing 'b' and 'c', both operands are strings, so no conversion takes place and the result is false (0).

    The first expression in your code can be rewritten as:

    ('a' = 'b') = 'c'
    

    Since ('a' = 'b') returns 0, after that operation has taken place, your expression will be interpreted as

    0 = 'c'
    

    Which is 1 because of the reason I explained above. Incidentally, this expression:

    'a' = 0 = 'c'
    

    Returns false, because ('a' = 0) returns 1 and then (1 = 'c') returns 0.

提交回复
热议问题