2013-03-05 154 views
2

我有表A作爲 | name1 | name2 | value |試圖避免重複查詢

表B爲|名|值|。

這裏的「名1」,並在表A「NAME2」屬性外鍵的表B中引用的「名」

現在我想有一個查詢功能是這樣的:

SELECT value FROM A WHERE name1 IN 
    (SELECT name FROM B WHERE value = '1') AND 
    name2 IN (SELECT name FROM B WHERE value = '1') 

這裏的問題是,如果我不喜歡它上面的代碼中,將有來自表B.兩個查詢,其實我只需要一個查詢,有沒有在SQL任何這樣寫道

SELECT value FROM A WHERE name1,name2 IN (SELECT name FROM B WHERE value = '1') 

而如果我想要這樣的東西:

SELECT value FROM A WHERE name1,name2 IN 
    (SELECT name FROM B ORDER BY value DESC FETCH FIRST 200 ROWS ONLY) 

+0

你正在使用什麼數據庫系統? – 2013-03-05 09:16:24

回答

0

可以加入嗎?

select value from A inner join table b b1 on a.name1 = b1.name inner join table b b2 on a.name2 = b2.name where b1.name = '1' and b2.name = '1'

+0

這裏我的問題是,A和B都非常大,如果我可以從B中首先選擇,將會有更少的元組,那麼加入這裏仍然會影響性能? – faz 2013-03-05 04:27:35

+0

它是否必須是純粹的查詢?你能把它包裝在一個函數或程序中嗎?在那種情況下,你可以聲明一個臨時表,並加入這個表? '聲明@tbl表(名字nvarchar);插入@tbl從B中選擇前200名;從A中選擇名稱,其中名稱1(從@tbl中選擇名稱)和名稱2(從@tbl中選擇名稱)' – AndrewP 2013-03-05 21:44:50

0

您可以使用加入這樣SELECT A.value FROM A inner join B on A.name1 = B.name inner join B on A.name2 = B.name where B.name in ('1')

+0

我的問題在於A和B都非常大,如果我可以先從B中選擇,少得多的元組,加入這裏仍然會影響性能? – faz 2013-03-05 04:32:09

+0

我認爲聯接比您使用的多級查詢更快。 – 2013-03-05 04:43:59

0
select name, value from b 
left outer join (select name1 from a where value = '1') as a1 on 
a1.name1 = b.name 
left outer join (select name2 from a where value = '1') as a2 on 
a2.name2 = b.name 
where value is not null 
/*omit null from left outer join for names not in table b*/ 
0

在SQLServer2005的+,你可以使用帶有NOT EXISTS + EXCEPT運營商

SELECT A.value 
FROM A 
WHERE NOT EXISTS (     
        SELECT A.name1 
        UNION 
        SELECT A.name2     
        EXCEPT 
        SELECT B.name 
        FROM B 
        WHERE B.value = '1'     
        ) 

SQLFiddle

0

演示選項創建表B中的視圖,並使用它呢?

Create view B_LIMITED AS SELECT name FROM B WHERE value = '1' 

select value from A inner join table b_limited b1 on a.name1 = b1.name inner join table b_limited b2 on a.name2 = b2.name where b1.name = '1' and b2.name = '1'