您好,我是小DAI,专注于数据库管理员相关的技术问答,请问有什么可以帮您?

basic_sql__select__ordery__by

SQL ORDER BY 关键字

  • ORDER BY 关键字用于对结果集按照一个列或者多个列进行排序。

  • ORDER BY 关键字默认按照升序对记录进行排序。如果需要按照降序对记录进行排序,您可以使用 DESC 关键字。

    SQL ORDER BY 语法

    SELECT column1, column2, ...
    FROM table_name
    ORDER BY column1, column2, ... ASC|DESC;
    column1, column2, ...:要排序的字段名称,可以为多个字段。

  • ASC:表示按升序排序。

  • DESC:表示按降序排序。

    演示数据库

    在本教程中,我们将使用 RUNOOB 样本数据库。

    下面是选自 "Websites" 表的数据:

    +----+--------------+---------------------------+-------+---------+
    +----+--------------+---------------------------+-------+---------+
    <table>
    <tr>
    <th>1</th>
    <th>Google</th>
    <th>https://www.google.cm/</th>
    <th>1</th>
    <th>USA</th>
    </tr>
    <tr>
    <td>3</td>
    <td>菜鸟教程</td>
    <td>http://www.runoob.com/</td>
    <td>4689</td>
    <td>CN</td>
    </tr>
    <tr>
    <td>4</td>
    <td>微博</td>
    <td>http://weibo.com/</td>
    <td>20</td>
    <td>CN</td>
    </tr>
    <tr>
    <td>5</td>
    <td>Facebook</td>
    <td>https://www.facebook.com/</td>
    <td>3</td>
    <td>USA</td>
    </tr>
    </table>
    
    +----+--------------+---------------------------+-------+---------+

    ORDER BY 实例

    下面的 SQL 语句从 "Websites" 表中选取所有网站,并按照 "alexa" 列排序:

    实例

    SELECT * FROM Websites
    ORDER BY alexa;

    ORDER BY DESC 实例

    下面的 SQL 语句从 "Websites" 表中选取所有网站,并按照 "alexa" 列降序排序:

    实例

    SELECT * FROM Websites
    ORDER BY alexa DESC;

    ORDER BY 多列

    下面的 SQL 语句从 "Websites" 表中选取所有网站,并按照 "country" 和 "alexa" 列排序:

    实例

    SELECT * FROM Websites
    ORDER BY country,alexa;

    来源:https://www.runoob.com/sql/sql-orderby.html