SQLite:Select n 到 n-y 范围内的最小值
SQLite: Select minimum value in a range from n to n-y
我有一个由 ID 和客户标识的订单列表。我需要知道从该客户放置的索引 n 的订单开始的索引 n-9 的订单的 id。
例如:
SELECT OrderID
FROM Orders
WHERE CustomerID = "1808317576" AND OrderID < 29
ORDER BY OrderID DESC LIMIT 9
上面的查询returns这些记录:
订单号
28
26
23
20
19
18
17
16
13
为了解决我的问题,我尝试这样做:
SELECT OrderID
FROM Orders
WHERE CustomerID = "1808317576" AND OrderID < 29
ORDER BY OrderID DESC LIMIT 1
我需要:
订单号
13
但是 returns 这个:
订单号
28
然后我尝试从 ORDER BY
中删除 DESC
:
SELECT OrderID
FROM Orders
WHERE CustomerID = "1808317576" AND OrderID < 29
ORDER BY OrderID LIMIT 1
但是 returns 这个:
订单号
1
怎样才能得到13?!
只需在相反(升序)方向子查询您当前的查询和顺序,限制为 1:
SELECT OrderID
FROM
(
SELECT OrderID
FROM Orders
WHERE CustomerID = '1808317576' AND OrderID < 29
ORDER BY OrderID DESC
LIMIT 9
) t
ORDER BY OrderID
LIMIT 1;
添加 OFFSET 8
以跳过返回的前 8 行并设置 LIMIT 1
:
SELECT OrderID
FROM Orders
WHERE CustomerID = '1808317576' AND OrderID < 29
ORDER BY OrderID DESC
LIMIT 1 OFFSET 8
或更简单:
SELECT OrderID
FROM Orders
WHERE CustomerID = '1808317576' AND OrderID < 29
ORDER BY OrderID DESC
LIMIT 8,1
我有一个由 ID 和客户标识的订单列表。我需要知道从该客户放置的索引 n 的订单开始的索引 n-9 的订单的 id。
例如:
SELECT OrderID
FROM Orders
WHERE CustomerID = "1808317576" AND OrderID < 29
ORDER BY OrderID DESC LIMIT 9
上面的查询returns这些记录:
订单号 |
---|
28 |
26 |
23 |
20 |
19 |
18 |
17 |
16 |
13 |
为了解决我的问题,我尝试这样做:
SELECT OrderID
FROM Orders
WHERE CustomerID = "1808317576" AND OrderID < 29
ORDER BY OrderID DESC LIMIT 1
我需要:
订单号 |
---|
13 |
但是 returns 这个:
订单号 |
---|
28 |
然后我尝试从 ORDER BY
中删除 DESC
:
SELECT OrderID
FROM Orders
WHERE CustomerID = "1808317576" AND OrderID < 29
ORDER BY OrderID LIMIT 1
但是 returns 这个:
订单号 |
---|
1 |
怎样才能得到13?!
只需在相反(升序)方向子查询您当前的查询和顺序,限制为 1:
SELECT OrderID
FROM
(
SELECT OrderID
FROM Orders
WHERE CustomerID = '1808317576' AND OrderID < 29
ORDER BY OrderID DESC
LIMIT 9
) t
ORDER BY OrderID
LIMIT 1;
添加 OFFSET 8
以跳过返回的前 8 行并设置 LIMIT 1
:
SELECT OrderID
FROM Orders
WHERE CustomerID = '1808317576' AND OrderID < 29
ORDER BY OrderID DESC
LIMIT 1 OFFSET 8
或更简单:
SELECT OrderID
FROM Orders
WHERE CustomerID = '1808317576' AND OrderID < 29
ORDER BY OrderID DESC
LIMIT 8,1