Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

mysql> SELECT 'a'='b'='c';
+-------------+
| 'a'='b'='c' |
+-------------+
|           1 |
+-------------+
mysql> select 'a'=0, 'b'='c';
+-------+---------+
| 'a'=0 | 'b'='c' |
+-------+---------+
|     1 |       0 | 
+-------+---------+

Why does 'a' equals 0 in MySQL?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...