MYSQL的流程控制语句

一、准备数据

create database ifTest;
use ifTest;
create table test(
    id int primary key auto_increment,
    typeId int not null comment '产品类型:1-普通商品 2-礼品卡 3-非卖品',
    productName varchar(50) not null comment '产品名称'
);
insert into test(typeId,productName) values(1,'可乐');
insert into test(typeId,productName) values(1,'西瓜');
insert into test(typeId,productName) values(1,'柠檬');
insert into test(typeId,productName) values(2,'100元礼品卡');
insert into test(typeId,productName) values(2,'200元礼品卡');
insert into test(typeId,productName) values(3,'航空纪念品');

二、CASE WHEN方案

select
CASE
WHEN [条件1] THEN [执行1]
WHEN [条件2] THEN [执行2]
ELSE [条件3]
END
from tableName;

select 
CASE 
WHEN typeId=1 THEN '普通商品'
WHEN typeId=2 THEN '普通商品'
ELSE '非卖品' 
END as typeName,
count(1) as productNum
from test
group by typeId;

三、if方案

select if(condition,TRUEResult,FALSEResult);

select 
sum(IF(typeId=1,1,0)) as '普通商品',
sum(IF(typeId=2,1,0)) as '礼品卡',
sum(IF(typeId=3,1,0)) as '非卖品'
from test;

四、总计

if和case when方式,各有各的优势,if可凑成横向结构,case when可以凑成纵向的结构。

你可能感兴趣的:(MYSQL)