Mysql 條件判斷Case 使用

2021-08-25 07:41:26 字數 1338 閱讀 9986

select substr(t1.area_id, 1, 1) type,

substr(t1.area_id, 2) id,

case substr(t1.area_id, 1, 1)

when 'c' then

(select t2.country

from countnumber.dbtable_countryid t2

where t2.id = substr(t1.area_id, 2))

else

(select distinct t3.province

from countnumber.dbtable_provinceid t3

where t3.id = substr(t1.area_id, 2))

end name

from t_ad_area t1

參考:*

case value

when [compare-value] then result

[when [compare-value] then result ...]

[else result]

end或

case

when [condition] then result

[when [condition] then result ...]

[else result]

end

在第乙個方案的返回結果中, value=compare-value。而第二個方案的返回結果是第一種情況的真實結果。如果沒有匹配的結果值,則返回結果為else後的結果,如果沒有else 部分,則返回值為 null。

mysql> select case 1 when 1 then 'one'

-> when 2 then 'two' else 'more' end;

-> 'one'

mysql> select case when 1>0 then 'true' else 'false' end;

-> 'true'

mysql> select case binary 'b'

-> when 'a' then 1 when 'b' then 2 end;

-> null

乙個case表示式的預設返回值型別是任何返回值的相容集合型別,但具體情況視其所在語境而定。如果用在字串語境中,則返回結果味字串。如果用在數字語境中,則返回結果為十進位制值、實值或整數值。

[url]

mysql條件控制case和if

if 和 ifnull 在做判斷時,case 是一種非常好用的方法 記住,沒有else會返回 null 整點資料測試一下 set foreign key checks 0 drop table ifexists customer create table customer obj id int 11...

MySQL條件判斷函式使用

1 case when express1 then value1 when express2 then value2 else value3 end as alias name 如果express1成立則取值value1,否則判斷express2是否成立,如果成立,取值value2,都不成立取值va...

case 條件語句

case 條件語句語法格式 case 變數 in值 1 指令1.值 2 指令2.指令3.esac 範例根據使用者輸入判斷使用者收入的是哪個數字 如果使用者輸入的是1 9的任易數字,則輸出對應輸入的數字 如果是其他數字級字元,則發回輸入不正確的提示,並退出 bin bash read p please...