如果条件大于返回值,请选择上一条记录

时间:2012-11-09 21:46:39

标签: mysql select

我正在尝试进行时间点查询以返回该时间点上次记录的数量。

基本上我有一个格式化的表

id | other_id | quantity | created
 1     1           5       20
 2     1           2       22
 3     1           1       25
 4     1           8       90

如果创建的查询是60,我想返回25和更高版本的创建数量 或者从查询创建以来最近已知的数量。

SELECT * FROM table
WHERE created >= 60
AND other_id = 1
ORDER BY ID ASC

返回ID:4,但我希望在60处创建的ID为3 但如果查询创建的是25,我想返回25和更高

大脑被油炸了,无法找到正确的解决方案

2 个答案:

答案 0 :(得分:1)

此查询选择所需值之前的值:

SELECT MAX(created)
FROM yourtable
WHERE other_id = 1
AND created <= 60

然后,您可以将其用作主查询中的子查询:

SELECT *
FROM yourtable
WHERE created >=
(
    SELECT IFNULL(MAX(created), -1)
    FROM yourtable
    WHERE other_id = 1
    AND created <= 60
)
AND other_id = 1
ORDER BY ID ASC

答案 1 :(得分:1)

SELECT * FROM table
WHERE id >= (
  SELECT id FROM table WHERE created <= 60
  AND other_id = 1
  ORDER BY id DESC LIMIT 1
)
AND other_id = 1
ORDER BY id ASC