2012-07-11 83 views
4

給定兩個表(每個表中的行是不同的):通過比較子集選擇記錄

1) x | y  z 2) x | y  z 
    ------- ---  ------- --- 
    1 | a  a  1 | a  a 
    1 | b  b  1 | b  b 
    2 | a    1 | c 
    2 | b    2 | a 
    2 | c    2 | b 
         2 | c 

有沒有辦法在第一臺的x列選擇的值,其值的子集在y列中,對於那個x,與第二個表的z列中的值完全匹配?

如果是1),預期結果爲1。如果c被添加到第二個表中,那麼預期的結果是2
如果2),預期結果是no record,因爲第一個表中的子集都不匹配第二個表中的子集。如果c被添加到第二個表中,那麼預期的結果是1, 2

我使用exceptintersect與第二個表,工作正常,比較第一個表的子集嘗試,但時間過久的intersect一部分,我想不通爲什麼(第一臺擁有約10.000條記錄,第二條約10條)。

編輯:我已經更新了問題以提供額外的場景。

回答

7
SELECT 
    table1.x 
FROM 
    table1 
INNER JOIN 
    table2 
    ON table1.y = table2.z 
GROUP BY 
    table1.x 
HAVING 
     COUNT(*) = (SELECT COUNT(*) FROM table2 AS lookup) 
    AND COUNT(*) = (SELECT COUNT(*) FROM table1 AS lookup WHERE x = table1.x) 
+0

不按要求工作:http://sqlfiddle.com/#!3/6d53d/1/0(_「如果c被添加到第二個表然後預期的結果是2「_) – 2012-07-11 13:32:20

+2

@TimSchmelter - 你的小提琴中有一個錯字。你可以在表1中插入'a,c,c'。它應該是'a,b,c'。 – MatBailie 2012-07-11 13:36:53

+0

你是對的+1 – 2012-07-11 13:39:17

1

其中一個會做

select 
    t1.x 
from 
    table1 as t1 inner join table2 as t2 on t1.x=t2.x 
group by t1.x 
having count(distinct t1.x)=count(distinct t2.x) 

select 
    t1.x 
from 
    table1 as t1 inner join table2 as t2 on t1.x=t2.x 
group by t1.x 
having count(distinct t1.x)=(select count(distinct x) from table2) 
+0

+1打我吧:) http://www.sqlfiddle.com/#!3/e15be/3。 – mellamokb 2012-07-11 13:20:29

+0

我認爲這不是數量,而是要獲得相同的數據。在這個例子中將工作,但在一個表中有10.000記錄不會 – 2012-07-11 13:21:17