2014-03-01 30 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; 
相关问题