Search code examples
mysqljoinconditional-statementsin-clause

SELECT subgroup of values


Given two tables 'Draws' (id, date) AND 'Results' (id, draw_id, number) where each Draw has x results, how can I get the draws that have a subgroup of numbers within their results?

Draws
-----------------
Id | Date
-----------------
1  | 2015-01-20
2  | 2015-01-22
-----------------

Results
--------------------
Id  | Draw | Number
--------------------
1   | 1    | 13
2   | 1    | 15
3   | 1    | 22
4   | 1    | 36
5   | 1    | 45
6   | 2    | 11
7   | 2    | 15
8   | 2    | 22

How can I get the draw that has (15,22,45) within its results? (In the example draw #1)


Solution

  • Good catch by Fred, this will return the correct results:

    SELECT
        d.*
    FROM
        Draw AS d
    INNER JOIN Results AS r1 ON r1.Draw = d.ID AND r1.Number = 15
    INNER JOIN Results AS r2 ON r2.Draw = d.ID AND r2.Number = 22
    INNER JOIN Results AS r3 ON r3.Draw = d.ID AND r3.Number = 45
    GROUP BY
        d.id;
    

    Fred's answer will work, but tbh it's fragile in that it will only work if you are looking for 3 results. My answer is more deliberate, however you will have to construct the query programatically to determine how many joins are necessary to get the results you want, for example:

    15 -> 1 join
    15, 22 -> 2 joins
    15, 22, 45 -> 3 joins
    ....