ORDER BY

ORDER BY 语法用于根据 SELECT 语句中的一个或多个列对数据进行升序或降序排序。

Syntax

ORDER BY 的基本语法如下:

sql

  1. SELECT column1, column2, ...
  2. FROM table_name
  3. ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...;

ORDER BY 可以用于一个或多个列。ASC 关键字用于升序排序(默认),DESC 关键字用于降序排序。

示例

假如我们有一个名为 system_metrics 的表:

sql

  1. +-------+-------+----------+-------------+-----------+---------------------+
  2. | host | idc | cpu_util | memory_util | disk_util | ts |
  3. +-------+-------+----------+-------------+-----------+---------------------+
  4. | host1 | idc_a | 11.8 | 10.3 | 10.3 | 2022-11-03 03:39:57 |
  5. | host1 | idc_b | 50 | 66.7 | 40.6 | 2022-11-03 03:39:57 |
  6. | host1 | idc_c | 50.1 | 66.8 | 40.8 | 2022-11-03 03:39:57 |
  7. | host1 | idc_e | NULL | 66.7 | 40.6 | 2022-11-03 03:39:57 |
  8. | host2 | idc_a | 80.1 | 70.3 | 90 | 2022-11-03 03:39:57 |
  9. +-------+-------+----------+-------------+-----------+---------------------+

要根据 memory_util 列对数据进行升序排序,可以使用以下 SQL 语句:

sql

  1. SELECT * FROM system_metrics
  2. ORDER BY memory_util ASC;

结果为:

sql

  1. +-------+-------+----------+-------------+-----------+---------------------+
  2. | host | idc | cpu_util | memory_util | disk_util | ts |
  3. +-------+-------+----------+-------------+-----------+---------------------+
  4. | host1 | idc_a | 11.8 | 10.3 | 10.3 | 2022-11-03 03:39:57 |
  5. | host1 | idc_b | 50 | 66.7 | 40.6 | 2022-11-03 03:39:57 |
  6. | host1 | idc_e | NULL | 66.7 | 40.6 | 2022-11-03 03:39:57 |
  7. | host1 | idc_c | 50.1 | 66.8 | 40.8 | 2022-11-03 03:39:57 |
  8. | host2 | idc_a | 80.1 | 70.3 | 90 | 2022-11-03 03:39:57 |
  9. +-------+-------+----------+-------------+-----------+---------------------+

要根据 disk_util 列对数据进行降序排序,可以使用以下 SQL 语句:

sql

  1. SELECT * FROM system_metrics
  2. ORDER BY disk_util DESC;

结果为:

sql

  1. +-------+-------+----------+-------------+-----------+---------------------+
  2. | host | idc | cpu_util | memory_util | disk_util | ts |
  3. +-------+-------+----------+-------------+-----------+---------------------+
  4. | host2 | idc_a | 80.1 | 70.3 | 90 | 2022-11-03 03:39:57 |
  5. | host1 | idc_c | 50.1 | 66.8 | 40.8 | 2022-11-03 03:39:57 |
  6. | host1 | idc_b | 50 | 66.7 | 40.6 | 2022-11-03 03:39:57 |
  7. | host1 | idc_e | NULL | 66.7 | 40.6 | 2022-11-03 03:39:57 |
  8. | host1 | idc_a | 11.8 | 10.3 | 10.3 | 2022-11-03 03:39:57 |
  9. +-------+-------+----------+-------------+-----------+---------------------+