如果记录存在,我想返回 bool 值。 以下查询适用于单个表。
SELECT CASE WHEN MAX(componentid) IS NULL THEN 'NO' ELSE 'YES' END
table3 FROM table3 WHERE componentid = 'GetAccountBalance';
我已经使用 JOIN 对 3 个表进行了相同的尝试,但我无法达到预期的结果。如果任何表(假设 table3)没有记录,则下面的查询将所有值返回为“否”其他两张表都有。
select CASE WHEN MAX(a.componentid)IS NULL THEN 'NO' ELSE 'YES' END table1,
CASE WHEN MAX(b.componentid)IS NULL THEN 'NO' ELSE 'YES' END table2,
CASE WHEN MAX(c.componentid)IS NULL THEN 'NO' ELSE 'YES' END table3
from table1 a
join table2 b on a.componentid=b.componentid
join table3 c on a.componentid=c.componentid
and a.componentid ='GetAccountBalance';
输出
table1 table2 table3
NO NO NO
预期
table1 table2 table3
YES YES NO
是否也可以使用 in 搜索多个值?喜欢
a.componentid in ('GetAccountBalance','GetCreditBalance')
最佳答案
你应该将其表述为exists
:
select (case when exists (select 1 from table1 where componentid = 'GetAccountBalance')
then 'YES' else 'NO'
end) as flagTable1,
(case when exists (select 1 from table2 where componentid = 'GetAccountBalance')
then 'YES' else 'NO'
end) as flagTable2,
(case when exists (select 1 from table3 where componentid = 'GetAccountBalance')
then 'YES' else 'NO'
end) as flagTable3
from dual;
进行连接的开销是完全没有必要的。上面的内容还应该优化使用表上的索引。
编辑:
对于多个组件,可以使用关联子查询:
select (case when exists (select 1 from table1 t1 where t1.componentid = c.componentid)
then 'YES' else 'NO'
end) as flagTable1,
(case when exists (select 1 from table2 t2 where t2.componentid = c.componentid)
then 'YES' else 'NO'
end) as flagTable2,
(case when exists (select 1 from table3 t3.where t3.componentid = c.componentid)
then 'YES' else 'NO'
end) as flagTable3
from (select 'GetAccountBalance' as componentid from dual union all
select 'GetCreditBalance' from dual
) c
关于sql - 如果存在多个表的记录,如何返回 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34703777/