我有一张如下表格:
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
失败后(分别由1
和0
给出)。当我说“跟随”时,我指的是同一个人之前的尝试,由较低的id
给出。
所以在这种情况下:
id = 5
成功,id = 3
失败,该人之前的尝试失败,因此符合标准。 我该怎么写这样的查询?
答案 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