1. 程式人生 > >SQL語句中case、when、then的使用

SQL語句中case、when、then的使用

使用語法為:select `pro`.`id` AS `id`,`pro`.`title` AS `title`,`pro`.`name` AS `name`,`pro`.`ltime` AS `ltime`,`pro`.`place` AS `place`,`pro`.`linkman` AS `linkman`,`pro`.`address` AS `address`,`pro`.`tel` AS `tel`,`pro`.`email` AS `email`,`pro`.`adder` AS `adder`,`pro`.`addtime` AS `addtime`,`pro`.`remark` AS `remark`,`prep`.`addtime` AS `addtime1`,`preplog`.`addtime` AS `addtime2`,

(case

 when (`prep`.`addtime` is not null) then '1' 

when ((`preplog`.`addtime` is not null) and isnull(`prep`.`addtime`)) then '2' 

else '0' end) AS `status` 

from ((`pro` left join `prep` on((`pro`.`id` = `prep`.`pid`))) left join `preplog` on((`pro`.`id` = `preplog`.`pid`))) where (`pro`.`type` = '認領資訊');

這裡主要注意的問題:

(1)as關鍵字主要是對欄位進行重新命名,可以忽略不寫;

(2)is not null 、is null、 isnull ()判斷欄位是否為空;

(3)(case  

        when     then  1

      when   then 2

     else   0  end ) as '';

  end 關鍵字不能缺少,as後面是對條件查詢結果的重新命名,也可以忽略;

(4)left join on 實現多表的連線,where 關鍵字是對多表連結結果的條件篩選。