SELECT
CASE 'abc'
WHEN true THEN 10
WHEN true THEN 20
WHEN false THEN 30
WHEN 'abc' THEN 40
end as abc
返回30
我预计40,10,至少20,但它给了30
答案 0 :(得分:2)
因为MySQL does not have a real boolean type:
常量
TRUE
和FALSE
分别评估为1
和0
。
Type conversion完成剩下的工作。我对确切的细节可能有误,但我知道这是适用的规则:
在所有其他情况下,参数将被比较为浮点(实数)。
由于abc
转为零,匹配的第一个值为false
:
mysql> SELECT CAST('abc' AS DECIMAL), false;
+------------------------+-------+
| CAST('abc' AS DECIMAL) | FALSE |
+------------------------+-------+
| 0 | 0 |
+------------------------+-------+
1 row in set, 1 warning (0.01 sec)
mysql> show warnings;
+---------+------+------------------------------------------+
| Level | Code | Message |
+---------+------+------------------------------------------+
| Warning | 1292 | Truncated incorrect DECIMAL value: 'abc' |
+---------+------+------------------------------------------+
1 row in set (0.00 sec)
在原始查询中,如果您要求提供警告消息,则可以进一步诊断:
mysql> SELECT
-> CASE 'abc'
-> WHEN true THEN 10
-> WHEN true THEN 20
-> WHEN false THEN 30
-> WHEN 'abc' THEN 40
-> end as abc;
+------+
| abc |
+------+
| 30 |
+------+
1 row in set, 1 warning (0.01 sec)
mysql> show warnings;
+---------+------+-----------------------------------------+
| Level | Code | Message |
+---------+------+-----------------------------------------+
| Warning | 1292 | Truncated incorrect DOUBLE value: 'abc' |
+---------+------+-----------------------------------------+
1 row in set (0.00 sec)
答案 1 :(得分:0)
SELECT table_name,
CASE [ expression ]
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n
ELSE result
END
FROM all_tables;
SELECT
CASE 'abc'
WHEN 'abc' THEN 10 -- True
WHEN 'abc' THEN 20 -- True
WHEN 'bca' THEN 30 -- False
WHEN 'abc' THEN 40 -- True
END
您将获得符合条件的第一个价值