1. 程式人生 > >MySql 函式 CASE WHEN THEN ELSE END 的用法

MySql 函式 CASE WHEN THEN ELSE END 的用法

CASE 的介紹

      Case 具有兩種格式,簡單的Case函式和Case搜尋函式

      簡單的Case函式:

      建立一張表並且新增資料:

/*
Navicat MySQL Data Transfer

Source Server         : MyDB
Source Server Version : 50720
Source Host           : localhost:3306
Source Database       : student

Target Server Type    : MYSQL
Target Server Version : 50720
File Encoding         : 65001

Date: 2018-11-01 16:42:00
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for person
-- ----------------------------
DROP TABLE IF EXISTS `person`;
CREATE TABLE `person` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `sex` int(2) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of person
-- ----------------------------
INSERT INTO `person` VALUES ('1', '1', '王');
INSERT INTO `person` VALUES ('2', '2', '張');

SQL示例:

SELECT
	p.id,
	p. NAME,
	CASE p.sex
WHEN 1 THEN
	"男"
WHEN 2 THEN
	"女"
ELSE
	"第三性別"
END sex
FROM
	person p

查詢結果:

CASE搜尋函式:

示例資料表:

/*
Navicat MySQL Data Transfer

Source Server         : MyDB
Source Server Version : 50720
Source Host           : localhost:3306
Source Database       : student

Target Server Type    : MYSQL
Target Server Version : 50720
File Encoding         : 65001

Date: 2018-11-01 16:56:42
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for courses
-- ----------------------------
DROP TABLE IF EXISTS `courses`;
CREATE TABLE `courses` (
  `courseno` varchar(20) NOT NULL,
  `coursenm` varchar(100) NOT NULL,
  PRIMARY KEY (`courseno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='課程表';

-- ----------------------------
-- Records of courses
-- ----------------------------
INSERT INTO `courses` VALUES ('C001', '大學語文');
INSERT INTO `courses` VALUES ('C002', '新視野英語');
INSERT INTO `courses` VALUES ('C003', '離散數學');
INSERT INTO `courses` VALUES ('C004', '概率論與數理統計');
INSERT INTO `courses` VALUES ('C005', '線性代數');
INSERT INTO `courses` VALUES ('C006', '高等數學(一)');
INSERT INTO `courses` VALUES ('C007', '高等數學(二)');

CASE 搜尋查詢語句

SELECT
	MAX(
		CASE
		WHEN c.courseno = 'C001' THEN
			'大學語文'
		ELSE
			'其他'
		END
	) 'yuwei',
	MAX(
		CASE
		WHEN c.courseno = 'C001' THEN
			'新視野英語'
		ELSE
			'其他'
		END
	) 'yingyu'
FROM
	courses c

查詢結果: