2014-03-01 60 views
0

這聽起來很混亂,我會盡量讓它更容易理解。如果存在符合標準的相應行,請選擇行?

有一個表,稱爲「會話」。

該列爲:rowid,time,user,action

我想要做的是選擇最後一個(最高rowid)x(假設4,它不是靜態的)會話,的動作爲1,但只有當行不存在時纔會有更大的時間列與行動0相同的用戶

所以,作爲一個例子,只有粗體行應選擇:

rowid(primary) time(epoch int) user action 
**152 1393635884 42 1** 
152 1392799204 75 1 
152 1392799416 42 0 *<-- the bolded row is selected because this exists with a greater time* 
152 1392802679 16 1 

如果這會有所幫助,它是如何發揮作用

SELECT * 
FROM sessions 
WHERE action = 1 AND there is a row where time > this time and user = this user and action = 0 
SORT BY rowid DESC 
LIMIT 4 

回答

0

僞的MySQL我相信你能做到你想用not exists條款:

SELECT s.* 
FROM sessions s 
WHERE s.action = 1 AND 
     not exists (select 1 
        from sessions s2 
        where s2.user = s.user and 
         s2.time > s.time and 
         s2.action = 0 
       ) 
ORDER BY rowid DESC 
LIMIT 4; 
相關問題