如何使用 MySQL ORDER BY 按值排序?

mysqlmysqli database

为此,请使用 ORDER BY 子句。让我们首先创建一个表 −

mysql> create table DemoTable
   (
   StudentId int
   );
Query OK, 0 rows affected (0.59 sec)

现在您可以使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(60);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(70);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(45);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable values(55);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(78);
Query OK, 1 row affected (0.14 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

输出

+-----------+
| StudentId |
+-----------+
| 100       |
| 60        |
| 70        |
| 45        |
| 55        |
| 78        |
+-----------+
6 rows in set (0.00 sec)

以下是使用 ORDER BY 按值排序的查询。这里,我们首先显示 70,因为我们已经使用 ORDER BY 设置了它的顺序。其余 ID 按升序显示−

mysql> select *from DemoTable order by StudentId=70 desc,StudentId asc;

输出

+-----------+
| StudentId |
+-----------+
| 70        |
| 45        |
| 55        |
| 60        |
| 78        |
| 100       |
+-----------+
6 rows in set (0.00 sec)

相关文章