2016-11-12 152 views
1

如果沒有查詢返回行,我希望能夠返回一行none, none, 0。我有這樣的SQL:sql - 如果行不存在,則返回一行常量值

select first, last, count(address) 
from employee 
where last in ('james', 'smith', 'hankers') 
group by first, last 
union all 
select 'none', 'none', 0 
from dual 
where not exists (select * from employee where last in ('james', 'smith', 'hankers')); 

從DB,用於jamessmith存在的條目,但沒有條目存在hankers

但是這個查詢只返回當條目存在時。不返回none, none, 0

我在這裏做錯了什麼?

編輯:在這個例子中,我傳遞3個硬編碼值爲last,但我想知道一個解決方法,如果我們通過getJdbcTemplate傳遞值作爲列表參數,如(:last)

+1

你可以使用的行數,喜歡這裏:http://stackoverflow.com/questions/2884996/simple-check-for-select-query-empty-result – aguetat

+0

你用哪個db? – vipin

+0

@vipin Oracle db – qollers

回答

0

應用NOT EXISTS考慮到全部的列出的值。因此,如果存在任何一個值,則不滿足NOT EXISTS

作爲一種變通,你可以使用一個在線表用指定的值和左加入您的原始表吧:

select coalesce(t2.first, 'none'), 
     coalesce(t2.last, 'none'), 
     count(t2.address) 
from (
    select 'james' as last 
    union all 
    select 'smith' 
    union all 
    select 'hankers') t1 
left join employee t2 ON t1.last = t2.last 
group by coalesce(t2.first, 'none'), 
     coalesce(t2.last, 'none') 

如果沒有匹配,就是這種情況的last='hankers',那麼count(t2.address)評估爲0,因此'none', 'none', 0被返回。

+0

我明白了。謝謝。但是,我應該在原始文章中進行澄清,但如果我們不知道「last」參數的確切大小,解決方法是什麼?在這個例子中,我傳遞了硬編碼的3個值作爲'last',但在我的實際SQL中,我不知道這些值,並且正在傳遞一個像這樣的列表參數:' – qollers

+0

@qollers另一個解決方法是用所有值填充臨時表。關於姓氏的信息必須存儲在某種關係結構中,如果你想檢索它的話。 –

0

也許這會幫助你,

_count NUMBER(10); 

select count(*) into _count 
from employee 
where last in ('james', 'smith', 'hankers'); 

if(_count > 0) 
then 
    select first, last, count(address) c 
    from employee 
    where last in ('james', 'smith', 'hankers') 
    group by first, last 
else 
    select 'none' first, 'none' last, 0 c from dual 
end if 
+0

'_count NUMBER(10);'我們在這裏聲明數字變量嗎?對不起,我的初學者是SQL – qollers

+0

如果你使用存儲過程來執行數據庫操作,你可以聲明變量。 – vipin

相關問題