简体   繁体   English

MySQL:选择值最接近但大于给定值的行

[英]MySQL: Select rows with values nearest but greater than a given value

Okay, I'm struggling here. 好吧,我在这里苦苦挣扎。 I have a MySQL table of unsorted values that is structured about like this: 我有一个未排序值的MySQL表,其结构如下:

ID     Size
-----  -----
1      12
2      10
3      1
4      0
5      8
6      9
7      6
8      2
9      9
10     4

What I'd like to do is given a size (eg size = 5) extract the next bigger rows (and the next smaller eventually). 给我想要的大小(例如size = 5),提取下一个较大的行(最终提取下一个较小的行)。

I've tried: 我试过了:

SELECT * FROM Table WHERE Size > 5 ORDER BY Size DESC LIMIT 2

But that gives me: 但这给了我:

ID     Size
-----  -----
1      12
2      10

but what I want is 但是我想要的是

ID     Size
-----  -----
7      6
5      8

Any help would be appreciated. 任何帮助,将不胜感激。 I'm using PHP to access the table if that makes a difference. 如果有区别,我正在使用PHP访问表。 Thanks! 谢谢!

You are using DESC that fetching result in descending . 您正在使用DESC来获取下降的结果。 you should use ASC that will fetch results in ascending. 您应该使用ASC来获取升序的结果。

Example- 例-

SELECT * FROM Table WHERE Size > 5 ORDER BY Size ASC LIMIT 2

EDITED 已编辑

You need to first fetch in descending order then you need to again order by ascending. 您需要先按降序获取,然后再按升序重新获取。

Example- 例-

  SELECT * FROM
    (SELECT * FROM Table WHERE Size > 5 ORDER BY Size DESC ) AS r
ORDER BY r.Size ASC LIMIT 2

You could select the rows having size greater 5 as a sub-query and select first two rows from the result set of the sub-query. 您可以选择大小大于5的行作为子查询,然后从子查询的结果集中选择前两行。

Query 询问

select t.* from(
  select * from your_table_name
  where size > 5
)t
order by t.size asc limit 2;

SQL Fiddle demo SQL Fiddle演示

您应该在ORDER BY子句中使用ASC,而不是DESC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM