我有一个这样的子查询
with subquery as (select host from table_A where << some condition >>)在我的主查询中,我从另一个名为table_B的表中查询数据,其中一列名为destination_host。现在我需要检查destination_host是否在从子查询返回的列表中,然后我想在select语句中输出TypeA,或者输出TypeB。我的select语句类似于
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但我不认为这是解决这个问题的方法。
发布于 2021-07-12 15:56:16
我会使用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;对于这样的查询,您必须注意空值。如果table_b.destination_host为NULL,该行将始终显示为typeB,因为NULL = NULL在SQL中不是TRUE。
https://stackoverflow.com/questions/68343678
复制相似问题