对于按距离排序,请使用ORDER BY ABS()
。让我们首先创建一个表-
mysql> create table DemoTable ( Number int );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values(100); mysql> insert into DemoTable values(101); mysql> insert into DemoTable values(102); mysql> insert into DemoTable values(103); mysql> insert into DemoTable values(104); mysql> insert into DemoTable values(105); mysql> insert into DemoTable values(106);
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+--------+ | Number | +--------+ | 100 | | 101 | | 102 | | 103 | | 104 | | 105 | | 106 | +--------+ 7 rows in set (0.00 sec)
以下是按距离排序的查询。在这里,n是103-
mysql> select *from DemoTable order by abs(103-Number);
这将产生以下输出-
+--------+ | Number | +--------+ | 103 | | 102 | | 104 | | 101 | | 105 | | 100 | | 106 | +--------+ 7 rows in set (0.17 sec)