我想过滤表中的特定值。应始终显示下一个较低的值。
+----+-----------+-------+------------+
| id | productid | lvl | value |
+----+-----------+-------+------------+
| 2 | 7 | 10 | 100 |
| 3 | 7 | 5 | 50 |
| 6 | 7 | 1 | 25 |
+----+-----------+--
如果我搜索lvl 6,应该会输出level 5。如果我搜索14级,应该会输出10级。
已尝试以下查询,但没有一个能按我想要的方式工作。例如,此查询适用于超过 4 的值。如果我使用低于 4 的值,我需要将 desc 更改为 asc 以获得正确的结果:
SELECT * FROM `levels` where lvl <= '6' ORDER BY lvl desc limit 1
使用 SQL 查询返回下一个较低(或等于)行的正确方法是什么?
最佳答案
我认为您的查询没有任何问题。它工作正常:
http://sqlfiddle.com/#!9/e567f/1
SELECT * FROM `levels` where lvl <= 6 ORDER BY lvl desc limit 1;
SELECT * FROM `levels` where lvl <= 14 ORDER BY lvl desc limit 1;
SELECT * FROM `levels_char` where lvl <= '6' ORDER BY lvl desc limit 1;
SELECT * FROM `levels_char` where lvl <= '14' ORDER BY lvl desc limit 1;
关于MySQL Select 查询返回错误行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30308569/