2013-05-07 59 views
0

我有一堆子查詢,每個子查詢都返回一堆帶有兩個ID字段的記錄。我需要返回所有子查詢中存在的所有ID對的列表。我想我可以做這樣的事情:查找所有子查詢中的常見值

SELECT Q1.V1, Q1.V2 
FROM ([SUBQUERY1]) AS Q1 
INNER JOIN ([SUBQUERY2]) AS Q2 ON Q2.V1 = Q1.V1 AND Q2.V2 = Q1.V2 
INNER JOIN ([SUBQUERY3]) AS Q3 ON Q3.V1 = Q2.V1 AND Q3.V2 = Q2.V2 
INNER JOIN ([SUBQUERY4]) AS Q4 ON Q4.V1 = Q3.V1 AND Q4.V2 = Q3.V2 

有沒有更好的辦法?

回答

0

顯然,答案是使用INTERSECT

[SUBQUERY1] 
INTERSECT 
[SUBQUERY2] 
INTERSECT 
[SUBQUERY3] 
INTERSECT 
[SUBQUERY4] 

不錯!

0

相交可能是更好的,但你也可以沿着用組HAVING COUNT(*)> number_of_subqueries條款。

select V1, V2 
from 
(
(subquery_1) 
union 
(subquery_2) 
union 
(subquery_3) 
) 
group by v1, v2 
having count(*) > 3