每天一个常用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)
相关推荐
-
PHP8种变量类型的详细讲解2025-02-22 00:32:24
-
php+apache 和 php+nginx的区别2025-02-22 00:21:27
-
PHP:与workerman结合实现定时任务2025-02-22 00:15:57
-
Nginx的Rewrite规则与实例2025-02-22 00:15:39
-
MySql中身份证字段的简单脱敏介绍2025-02-22 00:15:36