我有以下两个查询。如何将其修改为单个查询?如果任一查询返回数据,则结果应为true,否则为false:
select custId from customer where customerId=3425632456 and custPhone='5653663251';
select accountnumber from account where accountId=524526 and accountPhone='5653663251';
这里custPhone = accountPhone
最佳答案
我认为您想要exists
:
select case
when exists (select custId from customer where customerId=3425632456 and custPhone='5653663251')
then 1
when exists (select accountnumber from account where accountId=524526 and accountPhone='5653663251')
then 1
else 0
end res
from dual
此查询始终返回一行,并带有称为
res
的单列。如果任何子查询返回某些内容,则res
的值为1
,否则为0
。作为使用
case
的性能提升,如果第一个子查询成功,则不执行第二个子查询(这称为短路评估)。如果您的查询很耗时,这可能很有趣。确保先将价格较低的查询放在首位。如果您实际上要返回值,则有所不同。一种选择是
union all
:select custId from customer where customerId=3425632456 and custPhone='5653663251'
union all
select accountnumber from account where accountId=524526 and accountPhone='5653663251'
请注意,与第一个查询不同,这不能保证仅返回一行。根据您的数据,这可以提供任意数量的行,包括0。您可能需要进行其他强制转换以对齐数据类型。