选择另一个语句如果没有行返回Oracle

问题描述:

我在SQL方面很薄弱。我有一个有3列和基本选择语句的小表。选择另一个语句如果没有行返回Oracle

select intl, loc FROM test_table where p.country = 'UAE' 

但在某些情况下没有行返回,在这种情况下,我想从同一个表中选择另一个语句。

我发现下面的查询,但我不能得到它的工作。

select intl, loc FROM test_table 
    where p.country = 'UAE' 
    union all 
    select 'intl','Loc' from dual 
    where not exists (select intl, loc FROM test_table where p.country = 'Other') 

我知道它很简单,但我坚持了几个小时。 感谢名单

如果我正确理解你的要求,有一点不同的做法可能是这样的:

SELECT intl, loc from test_table WHERE p.country = 
(CASE WHEN (SELECT intl FROM test_table WHERE p.country='UAE' AND ROWNUM=1) IS NOT NULL THEN 'UAE' 
ELSE 'Other' END); 

它看起来像你想使用WHERE p.country =或其他任何一个值。因此,这个CASE决定是否选择第一个p.country值返回的东西(我们必须限制结果ROWNUM=1得到一个结果,否则案件将无法工作 - 它期望在WHEN之后的一个值)。如果它(IS NOT NULL),那么我们在我们的WHERE中使用该值,否则我们使用在ELSE之后指定的不同值。

+0

谢谢。这是我需要的 – ShB

你似乎想查询的是:

select intl, loc 
from test_table 
where p.country = 'UAE' 
union all 
select 'intl', 'Loc' from dual 
where not exists (select intl, loc from test_table where p.country = 'UAE'); 

国为NOT EXISTS应该是一样的原始查询。

+0

Iam得到错误 – ShB

+0

@ShB。 。 。这非常含糊。 –

select intl, loc 
from test_table 
where p.country = 'UAE' 
union all 
select intl, loc from test_table 
where not exists (select intl, loc from test_table where p.country = 'UAE'); 

这样比较好。