根据行增量选择

时间:2013-03-30 20:44:44

标签: mysql sql

我有一个像这样的MySQL数据库:

ID | Twin | Tloss
0  |  300 | 250     #first entry 
1  |  301 | 250     #win;  score 1 - 0
2  |  302 | 250     #win;  score 2 - 0
3  |  302 | 251     #lose: score 2 - 1
4  |  303 | 251     #win;  score 3 - 1 
5  |  304 | 251     #end of match1 : Win  4 - 1
6  |  304 | 252     #lose; score 0 - 1
7  |  304 | 253     #lose; score 0 - 2
8  |  304 | 254     #lose; score 0 - 3 
9  |  304 | 255     #end of match2 : Lose 0 - 4
10 |  304 | 256     #lose; score 0 - 1
11 |  305 | 253     #win;  score 1 - 1
12 |  306 | 254     #win;  score 2 - 1 
13 |  306 | 255     #lose; score 2 - 2
14 |  307 | 255     #win;  score 3 - 2 
15 |  307 | 256     #end of match3 : Draw 3 - 3

....

我想选择与匹配号“n”对应的所有ID, 考虑到一场比赛在他赢了4次或输了4次后就结束了,因为每场比赛的最大回合数是6,所以可以抽签。

我从1个月开始使用SQL很多但是我真的迷失了这个。

有人可以帮助我吗?

提前感谢你,

1 个答案:

答案 0 :(得分:1)

我假设上面的一些数据被破坏了(记录11-15,字段tloss;记录5应该是Win 4 - 1)。我也不知道数字300和250是什么以及它们如何在表中改变。有了这些假设,这个未经测试的SQL可能是你想要的:

(根据GordonLinoff的反馈修改)

SELECT @matchno := @matchno + 1 AS matchno
FROM (SELECT @matchno := 0) mn,
     (SELECT ID, Twin, Tloss, 
             IF((Twin - @twin) = 4
             OR (Tloss - @tloss) = 4
             OR ((Twin - @twin) = 3 AND (Tloss - @tloss) = 3),
                @twin := Twin AND @tloss := Tloss,
                0)
      FROM   matches, (SELECT @twin := 300, @tloss := 250) AS base
      WHERE  (Twin - @twin) = 4
      OR     (Tloss - @tloss) = 4
      OR     ((Twin - @twin) = 3 AND (Tloss - @tloss) = 3)
      ORDER BY ID
     ) endmatches