in、not in、exists、not exists 在postgresql中的处理

版权声明:本文为博主原创文章,转载请标明出处。 https://blog.csdn.net/ctypyb2002/article/details/84325408

os: centos 7.4
db: postgresql 11.1

# cat /etc/centos-release
CentOS Linux release 7.4.1708 (Core) 
# su - postgres -c "psql -c \"select version();\""
                                                 version                                                 
---------------------------------------------------------------------------------------------------------
 PostgreSQL 11.1 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-28), 64-bit
(1 row)

in、not in

with tmp_t0 as (
  select 'a'::varchar as c0 union all
  select 'b'::varchar as c0 union all
  select null as c0 
)
select *
  from tmp_t0 t0
 where 1=1
   and t0.c0 in ('a')
;

 c0 
----
 a
(1 row)

with tmp_t0 as (
  select 'a'::varchar as c0 union all
  select 'b'::varchar as c0 union all
  select null as c0 
)
select *
  from tmp_t0 t0
 where 1=1
   and t0.c0 not in ('a')
;

 c0 
----
 b
(1 row)

exists、not exists

with tmp_t0 as (
  select 'a'::varchar as c0 union all
  select 'b'::varchar as c0 union all
  select null as c0 
)
select *
  from tmp_t0 t0
 where 1=1
   and exists ( select 1 
                  from tmp_t0 t1 
				 where 1=1
				   and t1.c0 = 'a' 
				   and t0.c0 = t1.c0  
			   )
;

 c0 
----
 a
(1 row)


with tmp_t0 as (
  select 'a'::varchar as c0 union all
  select 'b'::varchar as c0 union all
  select null as c0 
)
select *
  from tmp_t0 t0
 where 1=1
   and not exists ( select 1 
                      from tmp_t0 t1 
				     where 1=1
				       and t1.c0 = 'a' 
					   and t0.c0 = t1.c0 
			       )
;

 c0 
----
 b
 
(2 rows)

根据这两种结果猜测,就是在postgresql里 null 值所在行压根就没有参与运算。

总结下和oracle在处理null时的异同点:

相同点:
in、exists 运算时,postgresql和oracle的处理方式相同,就是null值所在行压根就没有参与运算。

不同点:
not in、not exists 运算时,postgresql 排除null值所在行,然后参与运算,oracle只要发现运算列存在null值时,结果直接为空。

猜你喜欢

转载自blog.csdn.net/ctypyb2002/article/details/84325408