首页 > 代码库 > mysql case

mysql case

1.table

CREATE TABLE `lee`(
`id` INT(10) NOT NULL auto_increment,
`name` varchar(20) DEFAULT null,
`birthday` datetime DEFAULT null,
PRIMARY KEY(`id`)) ENGINE=INNODB DEFAULT CHARSET=utf8;

2.data

INSERT INTO lee(name,birthday) VALUES(‘sam‘,‘1990-01-01‘);
INSERT INTO lee(name,birthday) VALUES(‘lee‘,‘1980-01-01‘);
INSERT into lee(name,birthday) VALUES(‘jone‘,‘1985-06-01‘);

SELECT * from lee;

3.1例子1
SELECT name,
CASE
WHEN birthday>‘1981‘ THEN ‘old‘
WHEN birthday<‘1988‘ THEN ‘yong‘
ELSE ‘ok‘
END AS age
FROM lee;

3.2例子2
SELECT NAME,
CASE name
WHEN ‘sam‘ THEN ‘yong‘
WHEN ‘lee‘ THEN ‘handsome‘
ELSE ‘good‘
END as oldname
FROM lee;

3.2例子2

select name, birthday,
case
when birthday > ‘1983‘ then ‘yong‘
when name=‘lee‘ then ‘handsome‘
else ‘just so so‘ end AS so
from lee;

mysql case