coalesce函数表示可以返回参数中的第一个非空表达式,当你有N个参数时选取第一个非空值(从左到右)。
实例一:
select coalesce(null,"carrot","apple");
返回结果:carrot
mysql> select coalesce(null,"carrot","apple");
+---------------------------------+
| coalesce(null,"carrot","apple") |
+---------------------------------+
| carrot |
+---------------------------------+
实例二:
select coalesce(1,"carrot","apple")
返回结果:1
友情提示:coalesce里的参数如果是字符串的话,务必用单引号或者双引号廓起来;
这些语句可以直接在mysql里运行。
mysql> select coalesce(1,"carrot","apple");
+------------------------------+
| coalesce(1,"carrot","apple") |
+------------------------------+
| 1 |
+------------------------------+
1 row in set (0.00 sec)
实际用到在查询时有可能是null时,显示0,如下 :
mysql> select coalesce(null, 0);
+-------------------+
| coalesce(null, 0) |
+-------------------+
| 0 |
+-------------------+
1 row in set (0.00 sec)
mysql> select coalesce('1', 0);
+------------------+
| coalesce('1', 0) |
+------------------+
| 1 |
+------------------+
1 row in set (0.00 sec)
实例一:
select coalesce(null,"carrot","apple");
返回结果:carrot
mysql> select coalesce(null,"carrot","apple");
+---------------------------------+
| coalesce(null,"carrot","apple") |
+---------------------------------+
| carrot |
+---------------------------------+
实例二:
select coalesce(1,"carrot","apple")
返回结果:1
友情提示:coalesce里的参数如果是字符串的话,务必用单引号或者双引号廓起来;
这些语句可以直接在mysql里运行。
mysql> select coalesce(1,"carrot","apple");
+------------------------------+
| coalesce(1,"carrot","apple") |
+------------------------------+
| 1 |
+------------------------------+
1 row in set (0.00 sec)
实际用到在查询时有可能是null时,显示0,如下 :
mysql> select coalesce(null, 0);
+-------------------+
| coalesce(null, 0) |
+-------------------+
| 0 |
+-------------------+
1 row in set (0.00 sec)
mysql> select coalesce('1', 0);
+------------------+
| coalesce('1', 0) |
+------------------+
| 1 |
+------------------+
1 row in set (0.00 sec)
作者:jackxiang@向东博客 专注WEB应用 构架之美 --- 构架之美,在于尽态极妍 | 应用之美,在于药到病除
地址:https://jackxiang.com/post/4934/
版权所有。转载时必须以链接形式注明作者和原始出处及本声明!
评论列表