我有以下两个查询。如何将其修改为单个查询?如果任一查询返回数据,则结果应为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。您可能需要进行其他强制转换以对齐数据类型。
您可以在两个表上执行FULL OUTER JOIN
并使用CASE
语句检查计数:
SELECT
CASE
WHEN COUNT(*) > 0
THEN 'TRUE'
ELSE 'FALSE'
END result,
FROM
customer c
FULL OUTER JOIN
account a
ON c.custPhone = a.accountPhone
WHERE c.customerId=3425632456
AND a.accountId=524526
AND c.custPhone='5653663251;
尝试一下
select
custId,
accountnumber
from customer c
left join account a
on c.custPhone = a.accountPhone
where customerId = 3425632456
;