zoukankan      html  css  js  c++  java
  • MySQL-ISNULL()、IFNULL()和NULLIF()函数

    以下三个函数都可以用于where子条件,作为数据删除、更新的记录定位依据。

    如:

    SELECT * FROM usergrade WHERE ISNULL(USERNAME);

    一、ISNULL(expr)

    如果expr为null,那么isnull()的返回值为1,否则返回值为0。

    mysql> select isnull(1/0) as result;
    +--------+
    | result |
    +--------+
    |      1 |
    +--------+
    1 row in set (0.00 sec)
    
    mysql> select isnull(0/1) as result;
    +--------+
    | result |
    +--------+
    |      0 |
    +--------+
    1 row in set (0.00 sec)

    使用=的null值对比通常是错误的。 

    isnull()函数同is null比较操作符具有一些相同的特性。请参见有关is null 的说明。

    二、IFNULL(expr1,expr2)

    假如expr1不为NULL,不管expr2的值是否为NULL,IFNULL()的返回值为expr1;否则其返回值为expr2。

    IFNULL()的返回值是数字或是字符串,具体情况取决于其所使用的语境。

    mysql> SELECT IFNULL(1,0);
    +-------------+
    | IFNULL(1,0) |
    +-------------+
    |           1 |
    +-------------+
    1 row in set (0.01 sec)
    
    mysql> SELECT IFNULL(NULL,10); 
    +-----------------+
    | IFNULL(NULL,10) |
    +-----------------+
    |              10 |
    +-----------------+
    1 row in set (0.00 sec)
    
    mysql> SELECT IFNULL(1/0,10);  
    +----------------+
    | IFNULL(1/0,10) |
    +----------------+
    |        10.0000 |
    +----------------+
    1 row in set (0.00 sec)
    
    mysql> SELECT IFNULL(1/0,'yes'); 
    +-------------------+
    | IFNULL(1/0,'yes') |
    +-------------------+
    | yes               |
    +-------------------+
    1 row in set (0.00 sec)
    
    mysql> SELECT IFNULL(1,'yes'); 
    +-----------------+
    | IFNULL(1,'yes') |
    +-----------------+
    | 1               |
    +-----------------+
    1 row in set (0.00 sec)

    三、NULLIF(expr)

    如果expr1=expr2成立,那么返回值为NULL,否则返回值为expr1。

    mysql> select nullif(1,1);
    +-------------+
    | nullif(1,1) |
    +-------------+
    |        NULL |
    +-------------+
    1 row in set (0.00 sec)
    
    mysql> select nullif('a',1);
    +---------------+
    | nullif('a',1) |
    +---------------+
    | a             |
    +---------------+
    1 row in set, 1 warning (0.00 sec)
  • 相关阅读:
    centos安装vim
    thrift学习之二----学习资料积累
    thrift学习之一-------介绍
    组合模式
    一致性哈希算法(consistent hashing)
    php配置php-fpm启动参数及配置详解
    error while loading shared libraries的解決方法
    数据结构之二叉树
    768、最多能完成排序的块(贪心算法)
    VS code 配置C++编译环境
  • 原文地址:https://www.cnblogs.com/yy20141204bb/p/8419047.html
Copyright © 2011-2022 走看看