【问题标题】:postgres case statement with subquery带有子查询的 postgres case 语句
【发布时间】:2021-07-12 07:44:13
【问题描述】:

我有一个这样的子查询

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

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

【问题讨论】:

    标签: postgresql join case


    【解决方案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

    【讨论】:

    • 谢谢 Laurenz,我会试一试,告诉你我的进展情况
    猜你喜欢
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多