雪花,SQL where 子句

时间:2021-04-05 12:09:37

标签: sql snowflake-cloud-data-platform

我需要用 where 子句编写查询:

where       
    pl.ods_site_id in (select id from table1 where ...)

但是如果子查询(table1)没有返回任何东西,where子句不需要包含在结果查询中(就像它返回TRUE一样)。

我该怎么做? (我有雪花 SQL 方言)

2 个答案:

答案 0 :(得分:0)

您可以包含第二个条件:

where pl.ods_site_id in (select id from table1 where ...) or
      not exists (select id from table1 where ...)

这会显式检查子查询是否不返回任何行。

答案 1 :(得分:0)

如果您愿意使用 join 代替,Snowflake 支持 qualify 子句,这在这里可能会派上用场。您可以在 Snowflake 上运行此程序以查看其工作原理。

with 
pl (ods_site_id) as  (select 1 union all select 5),

table1 (id) as (select 5) --change this to 7 to test if it returns ALL on no match

select a.*
from pl a
left join table1 b on a.ods_site_id = b.id -- and other conditions you want to add
qualify b.id = a.ods_site_id --either match the join condition
        or count(b.id) over () = 0; --or make sure there is 0 match from table1