mysql - 如何在 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
我该怎么做?
解决方案
使用该WHERE
子句仅返回具有“更大”值的行。
SELECT *
FROM `elements`
where Length >= 20 and height >= 68
ORDER BY length + height
LIMIT 1
将ORDER BY
首先对长度 + 高度较小的行进行排序。用来LIMIT 1
挑选最小的。
推荐阅读
- javascript - 无法启动环境光传感器(Chrome、MacOS)
- r - 为什么我不能转化来平均这两个值?
- flutter - 在颤动中将 Html.File 转换为 Uint8List
- python - 如何将水平条形图转换为垂直图?
- kotlin - 调用 Coinbase pro 沙盒 api 时,无效:401 Unauthorized。文本:"{"message":"invalid signature"}" Kotlin
- html - 响应式导航 - 下拉链接
- angular - “ng-intercom”不会触发自定义小部件并且控制台中没有错误
- docker - 配置 Mutagen 以在 Kubernetes 内将主机文件与容器同步?
- angular - 如何测试 MatSideNav
- react-native - React Native 中最好的通知库是什么