MySQL CASE向后工作

时间:2012-10-15 19:59:01

标签: mysql case

我正在使用CASE来清理表中的一些状态缩写,但它与逻辑相反。我单独选择长度来表明正确计算长度,所以我认为这是CASE逻辑关闭

当我查询......

SELECT billing_state,
       length(billing_state),
       CASE billing_state
         WHEN length(billing_state) > 2 THEN (select state_abbr from lkup_states where upper(state_name) = billing_state)
         WHEN length(billing_state) = 2 THEN upper(billing_state)
         ELSE 'UNKNOWN'
       END as billing_state_fixed           
  FROM accounts
+---------------+-----------------------+---------------------+
| billing_state | length(billing_state) | billing_state_fixed |
+---------------+-----------------------+---------------------+
| GA            |                     2 | NULL                |
| Alabama       |                     7 | ALABAMA             |
| MS            |                     2 | NULL                |
| FL            |                     2 | NULL                |
| NULL          |                  NULL | UNKNOWN             |
+---------------+-----------------------+---------------------+

然而,当我进入这个奇怪的逻辑时,它的作用。

SELECT billing_state,
       length(billing_state),
       CASE billing_state
         WHEN length(billing_state) = 2 THEN (select state_abbr from lkup_states where upper(state_name) = billing_state)
         WHEN length(billing_state) <> 2 THEN upper(billing_state)
         ELSE 'UNKNOWN'
       END as billing_state_fixed           
  FROM accounts

+---------------+-----------------------+---------------------+
| billing_state | length(billing_state) | billing_state_fixed |
+---------------+-----------------------+---------------------+
| GA            |                     2 | GA                  |
| Alabama       |                     7 | AL                  |
| MS            |                     2 | MS                  |
| FL            |                     2 | FL                  |
| NULL          |                  NULL | UNKNOWN             |
+---------------+-----------------------+---------------------+

有人可以参加这个吗?

1 个答案:

答案 0 :(得分:1)

the docs,您的语法不太正确。

你混淆了CASE value WHEN compare_valueCASE WHEN expression

你可能想要的是:

SELECT billing_state,
       length(billing_state),
       CASE
         WHEN length(billing_state) > 2 THEN (select state_abbr from lkup_states where upper(state_name) = billing_state)
         WHEN length(billing_state) = 2 THEN upper(billing_state)
         ELSE 'UNKNOWN'
       END as billing_state_fixed           
  FROM accounts