-1

我不太清楚如何问这个问题,所以我将从一个例子开始。假设我的数据库中有一个如下所示的表:

id | time | event | pnumber
---------------------------
1  | 1200 | foo   | 23
2  | 1130 | bar   | 52
3  | 1045 | bat   | 13
...
n  | 0    | baz   | 7

现在说我想在一段时间后获得最后一个已知的 pnumber。例如,在时间 = 1135 时,它必须返回并在表中找到最后一个已知时间 (1130),然后返回该 pnumber。因此,对于 t = 1130,它将返回 pnumber = 52。但是一旦 t = 1045,它将返回 pnumber = 13。(在这种情况下,时间从 1200 倒计时到 0)。

这是我到目前为止所拥有的。

SELECT pnumber FROM table WHERE time = (SELECT time FROM table WHERE time <= '1135' ORDER BY time LIMIT 1)

有没有更简单的方法来做到这一点?不使用多个语句。我正在使用 sqlite3

4

3 回答 3

2

当然。您可以通过执行以下操作来压缩该查询:

SELECT pnumber FROM table WHERE time >= 1135 ORDER BY time DESC LIMIT 1;

无需嵌套选择以首先获取特定时间,这应该可以。

编辑:混合了不等式符号 - 如果您在特定时间之后寻找第一条记录,您将需要time >= 1135并按时间降序排列,限制为一个。

于 2013-07-18T20:06:54.820 回答
1

Why do you need the second query? Could you do something like this:

SELECT TOP 1 pnumber FROM table WHERE time  >= '1135' ORDER BY TIME DESC
于 2013-07-18T20:09:05.733 回答
1

I'm a bit confused. You are asking that 1135 would return the value for 1130, yet you are using greater than or equal to instead of less than. If your example is what you are looking for, try this.

SELECT PNUMBER FROM TABLE WHERE TIME<=1135 ORDER BY TIME DESC LIMIT 1
于 2013-07-18T20:10:20.443 回答