借助以下語法以兩列對MySQL 表進行排序-
order by yourColumnName1 DESC,yourColumnName2 DESC;
讓我們先為我們的範例建立一個表格-
mysql> create table OrderByDemo -> ( -> StudentId int, -> StudentName varchar(100), -> StudentAge int -> ); Query OK, 0 rows affected (0.57 sec)
借助insert指令向表中插入記錄。查詢如下 -
mysql> insert into OrderByDemo values(1,'John',23); Query OK, 1 row affected (0.20 sec) mysql> insert into OrderByDemo values(3,'Johnson',24); Query OK, 1 row affected (0.27 sec) mysql> insert into OrderByDemo values(4,'Carol',26); Query OK, 1 row affected (0.14 sec) mysql> insert into OrderByDemo values(2,'David',20); Query OK, 1 row affected (0.13 sec)
現在,應用上述語法對 MySQL 表中的兩個欄位進行排序。查詢如下 -
mysql> select *from OrderByDemo order by StudentId ASC, StudentAge ASC;
以下是按升序對兩列進行排序的輸出 -
+-----------+-------------+------------+ | StudentId | StudentName | StudentAge | +-----------+-------------+------------+ | 1 | John | 23 | | 2 | David | 20 | | 3 | Johnson | 24 | | 4 | Carol | 26 | +-----------+-------------+------------+ 4 rows in set (0.00 sec)
或您可以藉助 DESC 指令按降序執行。查詢如下 -
mysql> select *from OrderByDemo order by StudentId DESC,StudentAge DESC;
以下是輸出 -
+-----------+-------------+------------+ | StudentId | StudentName | StudentAge | +-----------+-------------+------------+ | 4 | Carol | 26 | | 3 | Johnson | 24 | | 2 | David | 20 | | 1 | John | 23 | +-----------+-------------+------------+ 4 rows in set (0.00 sec)
注意 - 主要排序首先起作用。
以上是以兩列對 MySQL 表進行排序?的詳細內容。更多資訊請關注PHP中文網其他相關文章!