case when使用
case when可以用在select后面,也可以用在order后面,也可以用在update后面。
case when语法:
case when condition1 then result1 when condition2 then result2 when conditionn then resultn else result end;
构建测试表:
drop table if exists `gold_product`; CREATE TABLE if not exists `gold_product`( `id` bigint NOT NULL AUTO_INCREMENT, `product_id` varchar(32) NOT NULL DEFAULT '' COMMENT '商品id', `app_type` varchar(32) NOT NULL DEFAULT '' COMMENT 'ios/android', `cost_stone` bigint NOT NULL COMMENT '花费钻石数', `num` bigint NOT NULL COMMENT '乐园币数', `status` varchar(32) NOT NULL DEFAULT '' COMMENT '上下架状态', `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci comment='乐园币套餐'; insert into gold_product (product_id,app_type,cost_stone,num,status) values ('0001','ios',10,1000,'上架'), ('0002','ios',60,6000,'上架'), ('0003','ios',120,12000,'上架'), ('0004','ios',300,30000,'上架'), ('0005','ios',1000,100000,'上架'), ('0006','ios',3000,300000,'上架'), ('0007','android',10,1000,'上架'), ('0008','android',60,6000,'上架'), ('0009','android',120,12000,'上架'), ('0010','android',300,30000,'上架'), ('0011','android',1000,100000,'上架'), ('0012','android',3000,300000,'上架');
场景1、用在select后面
需求:查gold_product表,如果app_type字段值是ios,则返回iOS,如果app_type字段值是android,则返回Android,其他情况返回app_type字段值。
select id,product_id, case when app_type='ios' then 'iOS' when app_type='android' then 'Android' else app_type end as app_type , cost_stone,num from gold_product;
场景2、用在order后面
需求:查gold_product表,如果cost_stone字段值在(100,1000)区间,则打8折,如果在[1000,3000)区间,则打6折,如果在[3000,+∞)区间,则打4折,否则不打折。按照这个值对gold_product表进行排序。
select * from gold_product order by case when cost_stone >100 and cost_stone <1000 then 0.8*cost_stone when cost_stone >=1000 and cost_stone <3000 then 0.5*cost_stone when cost_stone >=3000 then 0.1*cost_stone else cost_stone end;
场景3、用在update后面
需求,更新gold_product表,如果cost_stone字段值在(100,1000)区间,则打8折,如果在[1000,3000)区间,则打6折,如果在[3000,+∞)区间,则打4折,否则不打折。
update gold_product set update_time=now(),cost_stone= case when cost_stone >100 and cost_stone <1000 then 0.8*cost_stone when cost_stone >=1000 and cost_stone <3000 then 0.5*cost_stone when cost_stone >=3000 then 0.1*cost_stone else cost_stone end;
浙公网安备 33010602011771号