postgresql 逻辑和比较操作

逻辑操作

需要注意跟null值的与或操作

db01=> select true and null,true or null;
 ?column? | ?column? 
----------+----------
          | t
(1 row)

db01=> select false and null,false or null;
 ?column? | ?column? 
----------+----------
 f        | 
(1 row)

比较操作

between 比较中,and两边的值是包括进去的.这里需要注意!

db01=> select 1 between 1 and 3;
 ?column? 
----------
 t
(1 row)

db01=> select 1 between 3 and 1;
 ?column? 
----------
 f
(1 row)

默认[3,1]是没有值包括在内的.可以通过关键字SYMMETRIC来忽略and两边的顺序,有时候在程序中不清楚具体值的大小时会有用.

db01=> select 1 between symmetric 3 and 1;
 ?column? 
----------
 t
(1 row)

大家知道null值是不能使用=来比较的

db01=> select null=null,null!=null;
 ?column? | ?column? 
----------+----------
          | 
(1 row)

db01=> with t1(id,msg) as (
values(1,'aaa'),(2,'bbb'),(null,'ccc'),(4,'ddd')
),t2(id,amount) as (
values(2,100),(null,200),(5,700)
)select * from t1,t2 where t1.id = t2.id;
 id | msg | id | amount 
----+-----+----+--------
  2 | bbb |  2 |    100
(1 row)

那如果正好需求需要将null相同的一并列呢??

一种方法是使用coalesce,(pg中没有nvl函数吧?!)

db01=> with t1(id,msg) as (
values(1,'aaa'),(2,'bbb'),(null,'ccc'),(4,'ddd')
),t2(id,amount) as (
values(2,100),(null,200),(5,700)
)select * from t1,t2 where coalesce(t1.id,-1) = coalesce(t2.id,-1);
 id | msg | id | amount 
----+-----+----+--------
  2 | bbb |  2 |    100
    | ccc |    |    200
(2 rows)

需要注意 -1 这个值不能存在id这个列中.否则结果会出错

还有一种语法: is [not] distinct from 

db01=> with t1(id,msg) as (
values(1,'aaa'),(2,'bbb'),(null,'ccc'),(4,'ddd')
),t2(id,amount) as (
values(2,100),(null,200),(5,700)
)select * from t1,t2 where t1.id is not distinct from t2.id;
 id | msg | id | amount 
----+-----+----+--------
  2 | bbb |  2 |    100
    | ccc |    |    200
(2 rows)

//END

转载于:https://my.oschina.net/hippora/blog/379780

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值