SQL select table 1 或 table 2

SQL select either table 1 or table 2

我有以下两个问题。如何将其修改为单个查询?如果查询 returns 数据,结果应该为真,否则为假:

select custId from customer where customerId=3425632456 and custPhone='5653663251';

select accountnumber from account where accountId=524526 and accountPhone='5653663251';

这里custPhone=accountPhone

试试这个

select 
    custId,
    accountnumber 
from customer c
left join account a
on c.custPhone = a.accountPhone
where customerId = 3425632456 
;

我想你想要 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

此查询总是 return 单行,单列称为 res。如果任何子查询 return 是某物,则 res 具有值 1,否则 0.

作为使用 case 的性能奖励,如果第一个子查询成功则不会执行第二个子查询(这称为短路求值)。如果您的查询很耗时,这可能会很有趣;确保将成本较低的查询放在首位。


如果您真的想要 return 值,那就不同了。一种选择是 union all:

select custId from customer where customerId=3425632456 and custPhone='5653663251'
union all
select accountnumber from account where accountId=524526 and accountPhone='5653663251'

请注意,与第一个查询不同,这不能保证只有一行会被 returned。根据您的数据,这可能会给出任意数量的行,包括 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;