2014-09-29 52 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 
相關問題