MySQL数据库讲解条件判断函数 MySQL数据库使用教程

凤凰 2021-3-4 80 3/4

MySQL数据库讲解条件判断函数 MySQL数据库使用教程

函数:

(1)IF(expr,v1,v2)函数
(2)IFNULL(v1,v2)函数
(3)CASE函数

(相关免费学习推荐:mysql视频教程)

(1)if(expr,v1,v2)函数
  • 在if(expr,v1,v2)函数中,若表达式expr是true(expr<>0 and epr<>null)返回v1,否则返回v2。

【例】使用if()函数进行条件判断,SQL语句如下:

mysql> select if(1>2,2,3),
    -> if(1<2,'yes','no'),
    -> if(strcmp('test','test1'),'no','yes');+-------------+--------------------+---------------------------------------+| if(1>2,2,3) | if(1<2,'yes','no') | if(strcmp('test','test1'),'no','yes') |+-------------+--------------------+---------------------------------------+|           3 | yes                | no                                    |+-------------+--------------------+---------------------------------------+1 row in set (0.00 sec)

(2)ifnull(v1,v2)函数
  • 在ifnull(v1,v2)中,假如v1不为null,则ifnull()的返回值为v1,否则返回值为v2。
  • 如果v1或v2中只有一个明确是null,则if()函数的结果类型为非null表达式的结果类型。

【例】使用ifnull()函数进行条件判断,SQL语句如下:

mysql> select ifnull(1,2),ifnull(null,10),ifnull(1/0,'wrong');+-------------+-----------------+---------------------+| ifnull(1,2) | ifnull(null,10) | ifnull(1/0,'wrong') |+-------------+-----------------+---------------------+|           1 |              10 | wrong               |+-------------+-----------------+---------------------+1 row in set (0.00 sec)

(3)case函数

1.case expr when v1 then r1 [ when v2 then r2] [else rn] end

  • 该函数表示,如果expr值等于某个vi,则返回对应位置then后面的结果,如果与所有值都不相等,则返回else后面的m。

【例】使用case value when语句执行分支操作,SQL语句如下;

mysql> select case 2 when 1 then 'one' when 2 then 'two' else 'more' end;+------------------------------------------------------------+| case 2 when 1 then 'one' when 2 then 'two' else 'more' end |+------------------------------------------------------------+| two                                                        |+------------------------------------------------------------+1 row in set (0.00 sec)

2.case when v1 then rv [when v2 then r2] else rn] end

  • 该函数表示,某个vi值为true时,返回对应位置then后面的结果,如果所有值都不为true,则返回else后面的rn。
  • 一个case表达式的默认返回值类型是任何返回值的相容集合类型,具体情况视其所在语境而定。

【例】使用case when 语句执行分支操作,SQL语句如下:

mysql> select case when 1<0 then 'true' else 'false' end;+--------------------------------------------+| case when 1<0 then 'true' else 'false' end |+--------------------------------------------+| false                                      |+--------------------------------------------+1 row in set (0.00 sec)

更多相关免费学习推荐:mysql教程(视频)

以上就是MySQL讲解条件判断函数的详细内容,更多请关注本站其它相关文章!

- THE END -

凤凰

3月04日09:09

最后修改:2021年3月4日
0

非特殊说明,本博所有文章均为博主原创。