4

Given two tables (the rows in each table are distinct):

 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

Is there a way to select the values in the x column of the first table for which the subset of values in the y column, for that x, matches exactly the values in the z column of the second table?

In case 1), expected result is 1. If c is added to the second table then the expected result is 2.
In case 2), expected result is no record since neither of the subsets in the first table matches the subset in the second table. If c is added to the second table then the expected result is 1, 2.

I've tried using except and intersect to compare subsets of first table with the second table, which works fine, but it takes too long on the intersect part and I can't figure out why (the first table has about 10.000 records and the second has around 10).

EDIT: I've updated the question to provide an extra scenario.

2 Answers 2

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)
11
  • Doesn't work as desired: sqlfiddle.com/#!3/6d53d/1/0 ("If c is added to the second table then the expected result is 2") Commented Jul 11, 2012 at 13:32
  • 2
    @TimSchmelter - You have a typo in your fiddle. You insert a,c,c for set 2 in table 1. It should be a,b,c.
    – MatBailie
    Commented Jul 11, 2012 at 13:36
  • This assumes that there are no duplicates in the tables, which isn't asserted
    – Yellowfog
    Commented Jul 11, 2012 at 13:42
  • Shouldn't the count be on left side table? This way ABC will match AB because C record will not be counted. Commented Jul 11, 2012 at 13:45
  • 3
    I did - try this fiddle. It returns both 1 and 2. But changed to COUNT(DISTINCT table1.y) works correctly. Commented Jul 11, 2012 at 13:50
1

One of these will do

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)
1
  • I Think It's not about the quantity, it's about to got the same data. In that example will work, but in a table with 10.000 records won't
    – Gonzalo.-
    Commented Jul 11, 2012 at 13:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.