如何仅选择满足条件的最后一行?

问题描述:

我试图选择x = 5的行,但x不断变化。所以,我有这样一个表:如何仅选择满足条件的最后一行?

id x 
---- --- 
1  5 
2  6 
3  4 
4  5 
5  5 

所以我要像"SELECT * FROM table WHERE x=5 AND _???_;",使其返回行4 & 5,但行1

换句话说执行查询,我想x最近有这个值的行。我希望我明确自己。谢谢!

编辑: x后的条目数获得了我更改的最后一个值。我的意思是表也可以是这样的:

id x 
---- --- 
1  5 
2  6 
3  4 
4  5 
5  1 
6  5 
7  5 
... 5 
100 5 
101 5 

在这种情况下,它应该返回行[6-101]。

继西港岛线得到最近排

SELECT * FROM table WHERE x=5 ORDER BY id DESC LIMIT 0,1 
+0

是的,但这仍然会返回5,4和1,对不对? 我想自动停止x改变的地方,所以它永远不会返回1。 – marvin 2013-02-18 12:15:52

SQLFiddle demo

select * from t t1 
where 
x=(select x from t order by id desc limit 1) 
and 
not exists 
(select x from t where id>t1.id and x<>t1.x) 

SQLFiddle demo

select * from t t1 
where 
x=(select x from t order by id desc limit 1) 
and 
id>= 
(select max(id) from t 
    where x<> 
    (select x from t order by id desc limit 1) 
) 

选择什么是你的基础上速度更快。