Finding the lowest value in a table greater than a certain value

前端 未结 6 1017
臣服心动
臣服心动 2021-02-09 14:01

Say I have the following data

Name      Value
===============
Small        10
Medium      100
Large      1000

Imagine that these represent the

6条回答
  •  温柔的废话
    2021-02-09 14:27

    SELECT MAX(Value)
    FROM Table
    WHERE Value <= LEAST(@param,(SELECT MAX(Value) FROM Table))
    

    I'm not that familiar with Oracle but I'm sure it has a LEAST function or something equivalent.

    In any case, this query's subquery will be swift with the right index on the Value column.

    In all seriousness you really should do this in two queries (or two steps in one stored procedure if you want to keep them in the same place), because the second query is unnecessary if the first query works. Combining them in one query necessarily gives you an unconditional second (or sub-) query. You have to query the table twice, so the question is whether you query it twice always or just when necessary.

提交回复
热议问题