SQL:根据以前的ID查找

时间:2011-04-13 19:59:35

标签: mysql

我有一张如下表格:

mysql> select * from tries;
+----+--------+-----------+
| id | person | succeeded |
+----+--------+-----------+
|  1 |      1 |         1 |
|  2 |      1 |         1 |
|  3 |      2 |         0 |
|  4 |      4 |         1 |
|  5 |      2 |         1 |
|  6 |      2 |         0 |
|  7 |      3 |         0 |
|  8 |      3 |         0 |
|  9 |      3 |         0 |
| 10 |      1 |         0 |
| 11 |      4 |         1 |
| 12 |      4 |         1 |
+----+--------+-----------+

我希望那些({至少)一个try成功的人在try失败后(分别由10给出)。当我说“跟随”时,我指的是同一个人之前的尝试,由较低的id给出。

所以在这种情况下:

  • 第2个人id = 5成功,id = 3失败,该人之前的尝试失败,因此符合标准。
  • 第1个人没有立即跟随失败的成功,因此未通过标准
  • 第3个人没有成功,因此未达到标准
  • 第4个人没有失败,因此未通过标准

我该怎么写这样的查询?

2 个答案:

答案 0 :(得分:1)

Select ...
From tries As T
    Join tries As T2
        On T2.id = T.id + 1
            And T2.succeeded = 0
Where T.succeeded = 1

如果我们不能假设Ids是完全连续的:

Select ...
From tries As T
    Join    (
            Select T1.id, Min(T2.Id) As NextId
            From tries As T1
                Join tries As T2
                    On T2.id > T.id
            Group By T1.id
            ) As TriesAndNext
        On TriesAndNext.Id = T.Id
    Join tries As TNext
        On TNext.Id = TriesAndNext.NextId
            And TNext.succeeded = 0
Where T.succeeded = 1

答案 1 :(得分:1)

SELECT t1.person, MIN(t1.id) as SuccessID
    FROM tries t1
    WHERE t1.succeeded = 1
        AND t1.person IN (SELECT t2.person
                              FROM tries t2
                              WHERE t2.succeeded = 0
                                  AND t2.id < t1.id)
    GROUP BY t1.person