ORDER BY

  • 未指定排序规则,默认是升序排序。

    一级排序

    ```plsql

    如果没有使用排序操作.

    默认情况下查询返回的数据是按照添加数据的顺序显示的。

    SELECT * FROM employee;

使用 ORDER BY 对查询到的数据进行排序操作。

升序:ASC (ascend)

降序:DESC (descend)

练习:按照age从高到低的顺序显示信息

SELECT name, age, sport FROM employee ORDER BY age DESC;

SELECT name, age, sport FROM employee ORDER BY age;

如果在ORDER BY后没有显式指名排序的方式的话,则默认按照升序排列。

  1. ![image.png](https://cdn.nlark.com/yuque/0/2022/png/21705001/1642577254215-311a47b1-5542-4fc0-8c50-6317685ea7ba.png#clientId=u12906abf-5d57-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=186&id=uc6a84e13&margin=%5Bobject%20Object%5D&name=image.png&originHeight=186&originWidth=330&originalType=binary&ratio=1&rotation=0&showTitle=false&size=11493&status=done&style=none&taskId=u88a6ec3b-3361-4766-af95-f6a57b5379c&title=&width=330)![image.png](https://cdn.nlark.com/yuque/0/2022/png/21705001/1642577271730-1aec22b5-28fb-4595-b155-ff18b661b6a8.png#clientId=u12906abf-5d57-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=185&id=uab3ab4f7&margin=%5Bobject%20Object%5D&name=image.png&originHeight=185&originWidth=330&originalType=binary&ratio=1&rotation=0&showTitle=false&size=11525&status=done&style=none&taskId=u8d55d5ec-8e7a-4d1f-ad43-e7a34999959&title=&width=330)![image.png](https://cdn.nlark.com/yuque/0/2022/png/21705001/1642577288006-7f3ea444-8562-4114-a097-b48fb1a8f83d.png#clientId=u12906abf-5d57-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=188&id=u5ccc7bda&margin=%5Bobject%20Object%5D&name=image.png&originHeight=188&originWidth=262&originalType=binary&ratio=1&rotation=0&showTitle=false&size=9600&status=done&style=none&taskId=uad15b6b7-8193-485f-abf8-a6dab1b6e55&title=&width=262)<br />还可以通过别名排序
  2. ```plsql
  3. #我们可以使用列的别名,进行排序
  4. SELECT `name`, age * 2 D_age, sport
  5. FROM employee
  6. ORDER BY D_age;

列的别名只能在ORDER BY中使用,不能在WHERE中使用。
image.pngimage.png
WHERE需要声明在FROM后,ORDER BY之前。

  1. #强调格式:WHERE 需要声明在FROM后,ORDER BY之前。
  2. SELECT `name`, age, sport
  3. FROM employee
  4. WHERE age IN (17,20)
  5. ORDER BY age DESC;

image.png

二级排序

  1. #二级排序
  2. #按照age的降序排列,id的升序排列
  3. SELECT id, `name`, age, sport
  4. FROM employee
  5. ORDER BY age DESC,id ASC;

image.png