sql中的case when的使用
阿新 • • 發佈:2021-01-30
sql中的case when的使用
1.測試建表指令碼
CREATE TABLE `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(128) NOT NULL DEFAULT '' COMMENT '使用者名稱',
`gender` char(1) NOT NULL DEFAULT '' COMMENT '性別',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET =utf8 COMMENT='使用者表';
INSERT INTO `user` VALUES (1,'root1','男'),(2,'root2','男'),(3,'root3','女'),(4,'root4','女'),(5,'root5','0');
2.case when具體使用
表中原有資料
MariaDB [test]> select t1.id,t1.username , t1.gender from user t1; +----+----------+--------+ | id | username | gender | +----+----------+--------+ | 1 | root1 | 男 | | 2 | root2 | 男 | | 3 | root3 | 女 | | 4 | root4 | 女 | | 5 | root5 | 0 | +----+----------+--------+ 5 rows in set (0.000 sec)
Case具有兩種格式:簡單Case函式和Case搜尋函式。
顯然,簡單Case函式生在簡潔,但是它只適用於這種單欄位的單值比較,而Case搜尋函式的優點在於適用於所有比較的情況。
# 簡單Case函式 MariaDB [test]> select t1.id , t1.username , case when t1.gender='男' then 1 when t1.gender='女' then 2 else '未知' end as 性別 from user t1; +----+----------+------+ | id | username | 性別 | +----+----------+------+ | 1 | root1 | 1 | | 2 | root2 | 1 | | 3 | root3 | 2 | | 4 | root4 | 2 | | 5 | root5 | 未知 | +----+----------+------+ 5 rows in set (0.000 sec) # Case搜尋函式。 MariaDB [test]> select t1.id , t1.username , case t1.gender when '男' then 1 when '女' then 2 else '未知' end as 性別 from user t1; +----+----------+------+ | id | username | 性別 | +----+----------+------+ | 1 | root1 | 1 | | 2 | root2 | 1 | | 3 | root3 | 2 | | 4 | root4 | 2 | | 5 | root5 | 未知 | +----+----------+------+ 5 rows in set (0.000 sec)
3.總結
這兩種方式,可以實現相同的功能。簡單case函式的寫法相對比較簡潔,但是和case搜尋函式相比,功能方面會有些限制,比如寫判定式。