2

我正在尝试选择 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]。

4

2 回答 2

2

以下将获得最近的行

SELECT * FROM table WHERE x=5 ORDER BY id DESC LIMIT 0,1
于 2013-02-18T12:14:51.993 回答
1

SQLFiddle 演示

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 演示

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)
)

选择你的基地更快的东西。

于 2013-02-18T12:56:32.390 回答