SELECT子组值

时间:2016-01-13 20:20:07

标签: mysql join conditional in-clause

鉴于两个表'Draws'(id, date) AND'结果'(id, draw_id, number),其中每个Draw都有x个结果,如何在结果中获得具有数字子组的绘制?

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

如何在结果中获得(15,22,45)的平局? (在示例中绘​​制#1)

5 个答案:

答案 0 :(得分:1)

Fred很好地抓住了,这将返回正确的结果:

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;
弗雷德的回答是有效的,但是它很脆弱,因为它只会在你寻找3个结果时起作用。我的回答更加谨慎,但是你必须以编程方式构造查询以确定获得所需结果所需的连接数,例如:

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

答案 1 :(得分:0)

根据您的问题,您不需要加入任何内容......

select Draw from 
Results r
where r.Number in (15,22,45);

答案 2 :(得分:0)

这是另一种可能性(没有重复)

select * from Draws d where exists (select * from Results r where r.Draw=d.Id and Number in (1, 2, 3...) );

答案 3 :(得分:0)

您只需使用JOIN获取此结果

SELECT * FROM Draw, Results 
WHERE Draw.ID = Results.DrawID 
AND Results.Number IN (15,22,45);

结果:

您将获得结果ID (2,3,5,7,8)

答案 4 :(得分:0)

SELECT Draw FROM Results
Where Number IN (15,22,45)
Group By Draw
Having Count(*) > 2

只会为你提供全部3个

的抽奖
SELECT d.Date, r.Draw FROM #result r Join #Draws d ON d.id = r.Draw
Where Number IN (15,22,45)
Group By d.Date, r.Draw
Having Count(*) > 2

如果您想在结果中使用日期。