欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

mysql中IFNULL,IF,CASE的区别介绍

程序员文章站 2024-02-19 13:37:10
假设有一数据表的状态字段设计为varchar类型,有以下值:null,pending,pending refund,refund,cancel. 我们知道查询状态为canc...
假设有一数据表的状态字段设计为varchar类型,有以下值:null,pending,pending refund,refund,cancel.
我们知道查询状态为cancel的订单,sql语句可以这样写:select o.oid,o.moneyreceipt,o.moneyget,o.thecurrency,o.status from qorder o where o.status = 'cancel'
sql语句能查询出正确的数据,但是当我们想查询状态为非cancel的订单时,可能会出麻烦, 因为status字段没 有设置not null,所以大部分订单的status值都是null,这样的话,用'<>'查询出来的数据不正确,只有status除了cancel之外的非空数据查询出来了,而为null的没有查询出来。select o.oid,o.moneyreceipt,o.moneyget,o.thecurrency,o.status from qorder o where o.status <>'cancel'原 因:null值操作
null值可能令人感到奇怪直到你习惯它。概念上,null意味着“没有值”或“未知值”,且它被看作与众不同的值。为了测试null,你不能使用算术比较 操作符例如=、<或!=。为了说明它,试试下列查询:mysql> select 1 = null, 1 <> null, 1 < null, 1 > null;
+----------+-----------+----------+----------+
| 1 = null | 1 <> null | 1 < null | 1 > null |
+----------+-----------+----------+----------+
| null | null | null | null |
+----------+-----------+----------+----------+
很 显然你不能通过这些比较得到有意义的结果。相反使用is null和is not null操作符:mysql> select 1 is null, 1 is not null;
+-----------+---------------+
| 1 is null | 1 is not null |
+-----------+---------------+
| 0 | 1 |
+-----------+---------------+
请注意在mysql中,0或 null意味着假,而其它值意味着真。布尔运算的默认真值是1。根据以上的null值操作结果,最终使用此种方式解决:select o.oid,o.moneyreceipt,o.moneyget,o.thecurrency,o.status from qorder o where ifnull(o.status,'pending') <>'cancel'学习:ifnull(expr1,expr2)
如果expr1不是null,ifnull()返回expr1,否则它返回expr2。ifnull()返回一个数字或字符串值,取决于它被使 用的上下文环境。
复制代码 代码如下:

mysql> select ifnull(1,0); ->1
mysql> select ifnull(0,10); ->0
mysql> select ifnull(1/0,10); ->10.0000
mysql> select ifnull(1/0,'yes'); ->'yes'if(expr1,expr2,expr3)如果expr1是true(expr1<>0且expr1<>null),那么if()返回 expr2,否则它返回expr3。if()返回一个数字或字符串值,取决于它被使用的上下文。
mysql> select if(1>2,2,3); -> 3
mysql> select if(1<2,'yes','no'); -> 'yes'

(1) case value when [compare-value] then result [when [compare-value] then result ...] [else result] end //这个我还没想到咋用,知道的可以留言交流,
(2) case when [condition] then result [when [condition] then result ...] [else result] end //这个面试时被人问到了,可以用作条件判断
第(1)个返回 result,其中value=compare-value。第(2)个中如果第一个条件为真,返回result。如果没有匹配的result值,那么结 果在else后的result被返回。如果没有else部分,那么null被返回。
复制代码 代码如下:

mysql> select case 1 when 1 then "one" when 2 then "two" else "more" end; -> "one"
mysql> select case when 1>0 then "true" else "false" end; -> "true"
mysql> select case binary "b" when "a" then 1 when "b" then 2 end; -> null

上面的例子本人在mysql5.2.6上测试通过=====================================================================================ps:以上是转载的内容,觉得很不错就转过来了,其中的case...when...then、if、ifnull都是常用到的函数eg:select id,username,case gender when 1 then "男" when 2 then "女" end from t_people; select b.id,b.book_name,case b.type when 1 then "计算机" when 2 then "会计" else "其它" end from book b;