首页 > 解决方案 > 如何在 SQL 中选择最接近的值,但仅当该值更大时?

问题描述

我有一些数据下表:

+----+--------+--------+--------+-------+ 
| id | length | weight | height | width |
+----+--------+--------+--------+-------+
| 1  | 10     | 45     | 80     | 20    |
+----+--------+--------+--------+-------+
| 2  | 30     | 55     | 70     | 32    |
+----+--------+--------+--------+-------+
| 3  | 30     | 65     | 80     | 21    |
+----+--------+--------+--------+-------+

我想选择最接近长度和高度的值,但它必须大于我指示的值。例如,如果我在输入中写:

1)Length=20 and height=68 it should return id=2
2)Length=20 and height=71 it should return id=3

我试过这个(例如第一种情况),但我得到一个语法错误:

SELECT TOP 1 * FROM `elements` ORDER BY length-20 AND height-68

我该怎么做?

标签: mysqlsqlsql-order-byclosest

解决方案


使用该WHERE子句仅返回具有“更大”值的行。

SELECT *
FROM `elements`
where Length >= 20 and height >= 68
ORDER BY length + height
LIMIT 1

ORDER BY首先对长度 + 高度较小的行进行排序。用来LIMIT 1挑选最小的。


推荐阅读