带有子查询的 postgres case 语句

时间:2021-07-12 07:44:13

标签: postgresql join case

我有一个这样的子查询

with subquery as (select host from table_A where << some condition >>)

在我的主查询中,我从另一个名为 table_B 的表中查询数据,其中一列名为 destination_host。现在我需要检查destination_host 是否在我的子查询返回的列表中,然后我想在我的select 语句中输出TypeA,否则输出TypeB。我的选择语句看起来像

select name, place, destination_host
from table_B 
where <<some condition>>

我想输出基于条件检查的第四列,假设我们调用这个 host_category,如果 destination_host 值存在于子查询中,那么我想添加值 typeA 或 typeB。请你能帮我理解如何写这个。我知道如果您没有可使用的实际数据,则很难提供指导。

我尝试使用这样的 case 语句:

when (destination_host in (select host from subquery)) THEN 'typeA' 
when (destination_host not in (select host from subquery)) THEN 'typeB' 
end as host_category

但我不认为这是解决这个问题的方法。

1 个答案:

答案 0 :(得分:1)

我会使用EXISTS

WITH subquery AS (...)
SELECT CASE WHEN EXISTS (SELECT 1 FROM subquery
                         WHERE subquery.host = table_b.destination_host)
            THEN 'typeA'
            ELSE 'typeB'
       END
FROM table_b;

对于这样的查询,您必须处理 NULL 值。如果 table_b.destination_host 为 NULL,该行将始终显示为 typeB,因为 NULL = NULL 在 SQL 中不是 TRUE