有什么方法可以在 MySQL CASE 语句中对案例进行分组吗?
Is there any way for grouping cases in MySQL CASE statements?
是否有像 PHP switch 中那样编写 MySQL CASE 语句的缩写形式?例如,如果我有:
SELECT
CASE Type
WHEN 1 THEN "A"
WHEN 5 THEN "B"
WHEN 10 THEN "B"
WHEN 20 THEN "B"
WHEN 30 THEN "B"
WHEN 300 THEN "C"
ELSE "-"
END TypeDesc
在PHP语法中我们可以简单地写成:
switch ($Type) {
case 1: $TypeDesc = 'A'; break;
case 5:
case 10:
case 20:
case 30: $TypeDesc = 'B'; break;
case 300: $TypeDesc = 'C'; break;
default: $TypeDesc = '-'; }
我试过了:
WHEN 5 OR 10 OR 20 OR 30 THEN "B"
和
WHEN IN(5, 10, 20, 30) THEN "B"
还有这两个:
WHEN 5
WHEN 10
WHEN 20
WHEN 30 THEN "B"
WHEN 5 THEN
WHEN 10 THEN
WHEN 20 THEN
WHEN 30 THEN "B"
但是我得到不正确的结果或错误!
使用
case when <condition>
而不是
case <variable> when <value>
像这样
SELECT
CASE WHEN Type = 1 THEN "A"
WHEN Type < 300 THEN "B"
WHEN Type = 300 THEN "C"
ELSE "-"
END TypeDesc
是否有像 PHP switch 中那样编写 MySQL CASE 语句的缩写形式?例如,如果我有:
SELECT
CASE Type
WHEN 1 THEN "A"
WHEN 5 THEN "B"
WHEN 10 THEN "B"
WHEN 20 THEN "B"
WHEN 30 THEN "B"
WHEN 300 THEN "C"
ELSE "-"
END TypeDesc
在PHP语法中我们可以简单地写成:
switch ($Type) {
case 1: $TypeDesc = 'A'; break;
case 5:
case 10:
case 20:
case 30: $TypeDesc = 'B'; break;
case 300: $TypeDesc = 'C'; break;
default: $TypeDesc = '-'; }
我试过了:
WHEN 5 OR 10 OR 20 OR 30 THEN "B"
和
WHEN IN(5, 10, 20, 30) THEN "B"
还有这两个:
WHEN 5
WHEN 10
WHEN 20
WHEN 30 THEN "B"
WHEN 5 THEN
WHEN 10 THEN
WHEN 20 THEN
WHEN 30 THEN "B"
但是我得到不正确的结果或错误!
使用
case when <condition>
而不是
case <variable> when <value>
像这样
SELECT
CASE WHEN Type = 1 THEN "A"
WHEN Type < 300 THEN "B"
WHEN Type = 300 THEN "C"
ELSE "-"
END TypeDesc