2017-05-07 75 views
0

我在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') 

我知道它很簡單,但我堅持了幾個小時。 感謝名單

回答

0

如果我正確理解你的要求,有一點不同的做法可能是這樣的:

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

1

你似乎想查詢的是:

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。 。 。這非常含糊。 –

1
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'); 

這樣比較好。

相關問題