位置:首页 > 数据库 > SQL在线教程 > SQL排序结果

SQL排序结果

SQL ORDER BY子句用于对数据根据一个或一个以上的列按升序或降序进行排序。一些数据库默认排序查询结果按升序排列。

语法

ORDER BY子句的基本语法,将用于在升序或降序排列结果如下:

SELECT column-list 
FROM table_name 
[WHERE condition] 
[ORDER BY column1, column2, .. columnN] [ASC | DESC];

您可以在ORDER BY子句中使用多列。确保不管使用的是排序什么列,此列应该在 column-list 中。

例子:

考虑CUSTOMERS表具有以下记录:

+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
+----+----------+-----+-----------+----------+

下面是一个例子,这将结果通过NAME和SALARY按升序排序:

SQL> SELECT * FROM CUSTOMERS
     ORDER BY NAME, SALARY;

这将产生以下结果:

+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
+----+----------+-----+-----------+----------+

下面是一个例子,这将结果按NAME降序排序:

SQL> SELECT * FROM CUSTOMERS
     ORDER BY NAME DESC;

这将产生以下结果:

+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
+----+----------+-----+-----------+----------+

获取使用自己的优先顺序行,SELECT查询将如下:

SQL> SELECT * FROM CUSTOMERS
    ORDER BY (CASE ADDRESS
    WHEN 'DELHI' 	 THEN 1
    WHEN 'BHOPAL' 	 THEN 2
    WHEN 'KOTA' 	 THEN 3
    WHEN 'AHMADABAD' THEN 4
    WHEN 'MP' 	THEN 5
    ELSE 100 END) ASC, ADDRESS DESC;

这将产生以下结果:

+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
+----+----------+-----+-----------+----------+

这将在你自己喜欢的顺序首先在一个自然顺序,对剩余的地址按客户的ADDRESS进行排序。同时剩余的地址将在相反的字母顺序进行排序。