2014-09-29 53 views
1

我有一个包含用户登录数据表:选择MySQL的最后一行,并停止对匹配条件

------------------------------------ 
| ip   | timestamp | result | 
------------------------------------ 
| 12.34.56.78 | 12345671 | 0  | 
| 12.34.56.78 | 12345672 | 0  | 
| 12.34.56.78 | 12345673 | 1  | 
| 12.34.56.78 | 12345674 | 0  | 

result=0意味着登录失败,result=1意味着成功。

我的目标是选择表格的最后一行,其中result=0(按时间戳顺序排列),停止在第一行result=1处的选择。在所示的例子中,查询应该只返回最后一行。

我tryied以下

SELECT * FROM attempts WHERE ip="12.34.56.78" AND result=0 ORDER BY timestamp DESC; 

但它返回所有result=0行(为所需的IP)。我如何修改它在第一个result=1匹配停止?

回答

0

带电作业您用十字实现这个连接,以获得最大timestamp,其中结果为1,然后将其与外部查询的时间戳比较

select a.* 
from attempts a 
cross join(
    select max(`timestamp`) max_time 
    from attempts 
    where result=1 
    and ip='12.34.56.78' 
) t 
WHERE a.ip='12.34.56.78' 
and a.result=0 
and a.timestamp > t.max_time 

我已经添加了一些演示数据小提琴结果0和更大的时间戳从最后的结果= 1行的时间戳,它将返回它有更大的时间戳和结果行是0比较时间戳,其中结果是1

Demo

0

你可以在MySQL中使用“限制”命令:

SELECT * FROM attempts WHERE ip="12.34.56.78" AND result=0 ORDER BY timestamp DESC limit 1; 

它将返回最后一个条目匹配的标准。

+0

这是不对的,因为它没有考虑在其结果是1的时候 – 2014-09-29 10:19:36

1
select 
* 
from 
attempts 
where timestamp < (select timestamp from attempts where ip='12.34.56.78' and result = 1) 
and ip='12.34.56.78' and result = 0 
order by timestamp desc limit 1 
相关问题