Sql 在DB2上使用SELECT子句存在问题
我对在SELECT子句中使用EXISTS语句有点问题。我有表项和子项,如果存在给定类型的任何子项,我想返回布尔标志:Sql 在DB2上使用SELECT子句存在问题,sql,db2,exists,Sql,Db2,Exists,我对在SELECT子句中使用EXISTS语句有点问题。我有表项和子项,如果存在给定类型的任何子项,我想返回布尔标志: SELECT item.id, item.f1, item.f2, item.f3, EXISTS(select sub.id from schema.subitem sub where sub.item_id = item.id AND type='standard') as has_standard FROM schema.item item 但
SELECT item.id, item.f1, item.f2, item.f3,
EXISTS(select sub.id from schema.subitem sub where sub.item_id = item.id
AND type='standard') as has_standard
FROM schema.item item
但是,我收到了错误消息:
错误:[IBM][CLI Driver][DB2]SQL0104N出现意外的令牌“.”
找到以下“.”。预期代币可能包括:“,)”。
SQLSTATE=42601 SQLSTATE:42601错误代码:-104
该示例经过简化,表名不是真实的,它只是一个在DB2上询问EXISTS子句语法的示例。据我记忆所及,我在PostgreSQL或Oracle上使用该语法没有问题…在其周围放置一个
case
语句:
SELECT item.id, item.f1, item.f2, item.f3,
(case when EXISTS (select sub.id
from schema.subitem sub
where sub.item_id = item.id AND type='standard'
)
then 1 else 0
end) as has_standard
FROM schema.item item;
这些表的行数/行数分布如何?如果
项
很大,不管索引是什么,由于每个结果行都运行子查询,因此可能会导致系统的RBAR(逐行检查)LEFT JOIN
ing到DISTINCT
ed子查询可能会产生更好的性能。虽然此代码可以回答问题,但提供有关如何以及为什么解决问题的附加上下文将提高答案的长期价值。
SELECT item.id, item.f1, item.f2, item.f3,
CASE when (select '1' from schema.subitem sub
where sub.item_id = item.id AND type='standard')= '1'
then '1' else '0' end has_standard from schema.item item;