postgresql 的 is distinct from、is not distinct from

os: centos 7.4
db: postgresql 11.5

在 postgresql 开发过程中有时会用到 is distinct from 和 is not distinct from 这个功能

is distinct from

功能描述
A和B的数据类型、值不完全相同返回 true
A和B的数据类型、值完全相同返回 false
将空值视为相同。

postgres=# \x
Expanded display is on.
postgres=# select 1 is distinct from 1,
1 is distinct from 2,
1 is distinct from '1',
'1' is distinct from '1',
1 is distinct from null,
null is distinct from null
;
-[ RECORD 1 ]
?column? | f
?column? | t
?column? | f
?column? | f
?column? | t
?column? | f

is not distinct from

功能描述
A和B的数据类型、值不完全相同返回 false
A和B的数据类型、值完全相同返回 true
将空值视为相同。

postgres=# \x
Expanded display is on.
postgres=# select 1 is not distinct from 1,
1 is not distinct from 2,
1 is not distinct from '1',
'1' is not distinct from '1',
1 is not distinct from null,
null is not distinct from null
;
-[ RECORD 1 ]
?column? | t
?column? | f
?column? | t
?column? | t
?column? | f
?column? | t

第三条看起来有点不太符合规则

postgres=# select 1 is not distinct from '1';
-[ RECORD 1 ]
?column? | t

为 t ,这怎么理解了?

postgres=# select pg_typeof(1),pg_typeof('1');
-[ RECORD 1 ]------
pg_typeof | integer
pg_typeof | unknown

有意思吧,pg_typeof(‘1’) 居然是 unknown, 而我们把它想象成字符串了。

postgres=# select 1 is not distinct from cast('1' as varchar);
ERROR:  operator does not exist: integer = character varying
LINE 1: select 1 is not distinct from cast('1' as varchar);
                 ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

postgres=# select 1 is not distinct from cast('1' as int);
 ?column? 
----------
 t
(1 row)

postgres=# select cast('1' as varchar) is not distinct from 1;
ERROR:  operator does not exist: character varying = integer
LINE 1: select cast('1' as varchar) is not distinct from 1;
                                    ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

postgres=# select cast('1' as varchar) is not distinct from cast('1' as varchar);
 ?column? 
----------
 t
(1 row)

参考:

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

数据库人生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值