每天一个常用MySQL函数-if、isnull、ifnull等

场景
我们经常在数据存储如性别、类型此类的字段,一般使用tinyint来处理,那么展示的时候就需要用相应的文字值去展示,可以通过程序或者sql直接处理。对于一些类型字段如果数据库没有给默认值,那可能存入的是null,而有些却有值,那这种又该如何处理。
语法
if(expr,v1,v2) 如果expr为真则返回v1,否则返回v2
isnull(expr) 判断expr是否为null
ifnull(v1,v2) 如果v1存在则返回v1,否则返回v2
使用
--展示对应性别 if
select id,nickname,if(gender=1, '男', '女') as gender from user where id = 1565543;
+---------+-----------+--------+
| id | nickname | gender |
+---------+-----------+--------+
| 1565543 | 马小桶 | 男 |
+---------+-----------+--------+
1 row in set (0.00 sec)
--ifnull
select id, email, gender from user where id =5515;
+------+-------+--------+
| id | email | gender |
+------+-------+--------+
| 5515 | NULL | 2 |
+------+-------+--------+
1 row in set (0.00 sec)
select id,ifnull(email, '暂无邮箱') as email from user where id = 5515
+------+--------------+
| id | email |
+------+--------------+
| 5515 | 暂无邮箱 |
+------+--------------+
1 row in set (0.00 sec)
--isnull
select id, if(isnull(email), '暂无邮箱', email) as email from user where id = 5515;
+------+--------------+
| id | email |
+------+--------------+
| 5515 | 暂无邮箱 |
+------+--------------+
1 row in set (0.01 sec)
select id, if(isnull(email), '暂无邮箱', email) as email from user where id = 1561977;
+---------+---------------------+
| id | email |
+---------+---------------------+
| 1561977 | swsujianhua@163.com |
+---------+---------------------+
1 row in set (0.00 sec)
相关推荐
-
MySQL 安装失败,提示Apply Security Settings 的处理办法
MySQL 安装失败,提示Apply Security Settings 的处理办法2025-04-20 01:54:57 -
MySQL事务隔离级别详解2025-04-20 01:44:01
-
一文说清nginx规则匹配(含案例分析)2025-04-20 01:10:02
-
运维服务篇:Nginx常用功能(rewrite重定向/location定位等)
运维服务篇:Nginx常用功能(rewrite重定向/location定位等)2025-04-20 00:55:25 -
php定义变量规则不能包含哪些字符?2025-04-20 00:27:24