Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select records by comparing subsets

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.

like image 562
devnull Avatar asked Feb 19 '23 21:02

devnull


1 Answers

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)
like image 200
MatBailie Avatar answered Mar 03 '23 14:03

MatBailie