MySQL使用IF语句及用case语句对条件并结果进行判断
一、前期准备
CREATE TABLE `t1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`jgid` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
INSERT INTO `avlicy`.`t1`(`id`, `name`, `jgid`) VALUES (1, ‘二二’, 2);
INSERT INTO `avlicy`.`t1`(`id`, `name`, `jgid`) VALUES (2, ‘李四’, 2);
INSERT INTO `avlicy`.`t1`(`id`, `name`, `jgid`) VALUES (4, ‘七七’, 3);
INSERT INTO `avlicy`.`t1`(`id`, `name`, `jgid`) VALUES (5, ‘小猕猴’, 1);
INSERT INTO `avlicy`.`t1`(`id`, `name`, `jgid`) VALUES (6, ‘小米粥’, 1);
INSERT INTO `avlicy`.`t1`(`id`, `name`, `jgid`) VALUES (7, ‘小哈吧’, 1);
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`jgid` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
INSERT INTO `avlicy`.`t1`(`id`, `name`, `jgid`) VALUES (1, ‘二二’, 2);
INSERT INTO `avlicy`.`t1`(`id`, `name`, `jgid`) VALUES (2, ‘李四’, 2);
INSERT INTO `avlicy`.`t1`(`id`, `name`, `jgid`) VALUES (4, ‘七七’, 3);
INSERT INTO `avlicy`.`t1`(`id`, `name`, `jgid`) VALUES (5, ‘小猕猴’, 1);
INSERT INTO `avlicy`.`t1`(`id`, `name`, `jgid`) VALUES (6, ‘小米粥’, 1);
INSERT INTO `avlicy`.`t1`(`id`, `name`, `jgid`) VALUES (7, ‘小哈吧’, 1);
二、IF语句
1、场景一
如果id是基数则是,否则则否
SELECT
t1.*,
IF(MOD(t1.id,2)=0 ,’是’,’否’) AS 是否被二整除
FROM
t1
t1.*,
IF(MOD(t1.id,2)=0 ,’是’,’否’) AS 是否被二整除
FROM
t1
2、场景二
如果id是偶数则判断id是否与jgid相等,如果Id是奇数则判断id是否与jgid不相等
SELECT
t1.*
FROM
t1
WHERE
IF( MOD ( t1.id, 2 )= 0, id = jgid, id <> jgid )
t1.*
FROM
t1
WHERE
IF( MOD ( t1.id, 2 )= 0, id = jgid, id <> jgid )
三、CASE语句
根据jgid赋予不同的角色
SELECT
*,
CASE
WHEN jgid = 1 THEN
‘学生’
WHEN jgid = 2 THEN
‘教师’
WHEN jgid = 3 THEN
‘家长’ ELSE ”
END AS ‘角色’
FROM
t1
*,
CASE
WHEN jgid = 1 THEN
‘学生’
WHEN jgid = 2 THEN
‘教师’
WHEN jgid = 3 THEN
‘家长’ ELSE ”
END AS ‘角色’
FROM
t1
到此这篇关于MySQL使用IF语句及用case语句对条件并结果进行判断 的文章就介绍到这了,更多相关MySQL IF语句 内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!