2013-08-29 53 views
3

我已閱讀並閱讀並閱讀,但我沒有找到解決我的問題的方法。返回沒有匹配的行

我做這樣的事情:

SELECT a 
FROM t1 
WHERE t1.b IN (<external list of values>) 

當然也有其他的條件,但是這是它的JIST。

我的問題是:有沒有辦法顯示在手動輸入的值列表中找不到匹配項?我看了,但我找不到,我正在圈圈。

+0

類似的問題,也許是:http://stackoverflow.com/questions/8953163/ –

回答

3

創建值的外部列表中的臨時表,那麼你可以做:

select item 
    from tmptable t 
where t.item not in (select b from t1) 

如果列表足夠短,你可以這樣做:

with t as (
select case when t.b1='FIRSTITEM' then 1 else 0 end firstfound 
     case when t.b1='2NDITEM' then 1 else 0 end secondfound 
     case when t.b1='3RDITEM' then 1 else 0 end thirdfound 
     ... 
    from t1 wher t1.b in 'LIST...' 
) 
select sum(firstfound), sum(secondfound), sum(thirdfound), ... 
    from t 

但適當的權利,我會用Nicholas' answer

+0

我害怕的是,想看看它在進行之前沒有這個可能。謝謝。 – user2723016

0

有許多方法可以獲得您所描述的內容,但它們的要求超出了問題的說明。從提供的最小描述中,無法讓SQL返回不匹配的手動輸入值的列表。

例如,如果有可能的手動輸入的值插入到一個單獨的表 - 我們稱之爲matchtbl,與列名爲b - 那麼下面應該做的工作:

SELECT matchtbl.b 
FROM matchtbl 
WHERE matchtbl.b NOT IN (SELECT distinct b 
         FROM t1) 

當然如果數據正在被編程語言處理,通過將b列添加到輸出中,應該相對容易地跟蹤原始查詢返回的一組值,然後執行設置差異。

2

要顯示其在值列表值還沒有找到一個匹配,作爲方法之一,你可以創建一個嵌套表的SQL(架構對象)數據類型:

-- assuming that the values in the list 
-- are of number datatype 

create type T_NumList as table of number; 

,並用它如下:

-- sample of data. generates numbers from 1 to 11 
SQL> with t1(col) as(
    2  select level 
    3  from dual 
    4 connect by level <= 11 
    5 ) 
    6 select s.column_value as without_match 
    7 from table(t_NumList(1, 2, 15, 50, 23)) s -- here goes your list of values 
    8 left join t1 t 
    9  on (s.column_value = t.col) 
10 where t.col is null 
11 ; 

結果:

WITHOUT_MATCH 
------------- 
      15 
      50 
      23 

SQLFiddle Demo

+0

這將工作,但仍然需要在查詢之外創建一個對象。無論如何,我似乎都無法避免這種情況。 – user2723016

1

沒有簡單的方法將「外部提供」列表轉換爲可用於比較的表格。一種方法是使用(無證)系統類型之一,以產生基於提供的值飛的表:

with value_list (id) as (
    select column_value 
    from table(sys.odcinumberlist (1, 2, 3)) -- this is the list of values 
) 
select l.id as missing_id 
from value_list l 
left join t1 on t1.id = l.id 
where t1.id is null; 
+0

只是爲了確認 - 這樣做會創建一個持久表?或者只會在選擇查詢解決時才存在? – user2723016

+0

@ user2723016:不,這不會創建任何數據庫對象。帶有ID的「表格」是「即時」生成的。它與Gordon的答案(只是沒有醜陋的UNION ALL)和Nicholas的答案(只是沒有創建對象類型)基本上是一樣的想法 –

0

把在in條款清單,使這一努力。如果你可以把一個表中的列表,然後以下工作:

with list as (
     select val1 as value from dual union all 
     select val2 from dual union all 
     . . . 
     select valn 
    ) 
select list.value, count(t1.b) 
from list left outer join 
    t1 
    on t1.b = list.value 
group by list.value; 
+0

我知道,但我想看看是否有辦法做到這一點,而沒有在將SQL提供給dbas之前創建一個臨時表或類似的表。 – user2723016

+0

@ user2723016。 。 。 CTE('with'語句中的表達式)不是臨時表。事實上,你可以在沒有'with'的情況下編寫它,只需將它作爲子查詢。 –