2012-01-11 105 views
2

我有如下定義的表FOO:有沒有辦法選擇SQL中成對列表中的行?


id INTEGER, 
type INTEGER, 
data VARCHAR(32), 
PRIMARY KEY(id, type) 

我給對的列表:(ID,類型),我想所有這些對應於那些對(與沿數據ID和類型,所以我知道什麼屬於什麼)。我可以在一個查詢中做到這一點嗎? (我的SQL的特定方言是SQLite)

+0

標準SQL只有一個數據結構:行表。我認爲SQLite沒有「對」或「列表」的數據結構。請根據表格,行,列,標量參數等說明您的要求。謝謝。 – onedaywhen 2012-01-12 09:10:22

回答

2

在SQLite中這樣做的唯一方法是在where子句中執行一堆or語句。或者,你可以這樣做:

select 
    f1.* 
from 
    foo f1 
    inner join (
     select 'id1' as id, 'type1' as type union all 
     select 'id2', 'type2' union all 
     select 'id3', 'type3' 
    ) f2 on 
     f1.id = f2.id 
     and f1.type = f2.type 

對於薰陶,在where條款的做法是:

select 
    * 
from 
    foo 
where 
    (id = 'id1' and type = 'type1') 
    or (id = 'id2' and type = 'type2') 
    or (id = 'id3' and type = 'type3') 
+0

難道哪裏的方法執行速度更快? – chacham15 2012-01-11 19:33:21

+0

@ chacham15 - 不一定。 '或'可以真的搞砸了性能。 「內部連接」將建立一個散列表並快速加入表格,而不是通過謂詞列表。話雖如此,試試看看哪一個更快。我通常在SQL Server中工作,其中where子句中的「or」是死亡跪拜。 – Eric 2012-01-11 19:36:52

0

如果你有很多對,你也可以有第二個表抱着對。

select 
    foo.* 
from 
    foo 
    inner join pairs 
     on foo.id = pairs.id and foo.type = pairs.type 
相關問題