介紹如何在 MySQL/MariaDB 資料庫中使用 ORDER BY
排序 SELECT
的查詢結果。
首先建立一張 person
資料表,並且插入了一些資料:
-- 建立 persons 資料表 CREATE TABLE persons ( id INT NOT NULL AUTO_INCREMENT, -- 序號,整數、非空、自動遞增 name VARCHAR(255), -- 名字,可變長度的文字 age INT UNSIGNED, -- 年齡,非負整數 city ENUM('Taipei', 'Hsinchu', 'Kaohsiung'), -- 所在城市,固定選項 PRIMARY KEY (id) -- 主鍵 ); -- 插入多筆資料至 persons 資料表 INSERT INTO persons (name, age, city) VALUES ("Hill", 21, "Kaohsiung"), ("Bond", 34, "Taipei"), ("Arden", 32, "Taipei"), ("Cole", 12, "Hsinchu"), ("Bell", 16, "Kaohsiung"), ("Dana", 19, "Hsinchu"); -- 查看 persons 資料表內所有資料 SELECT * FROM persons;
+----+-------+------+-----------+ | id | name | age | city | +----+-------+------+-----------+ | 1 | Hill | 21 | Kaohsiung | | 2 | Bond | 34 | Taipei | | 3 | Arden | 32 | Taipei | | 4 | Cole | 12 | Hsinchu | | 5 | Bell | 16 | Kaohsiung | | 6 | Dana | 19 | Hsinchu | +----+-------+------+-----------+
依照 age
排序結果:
-- 以 age 排序 SELECT * FROM persons ORDER BY age;
+----+-------+------+-----------+ | id | name | age | city | +----+-------+------+-----------+ | 4 | Cole | 12 | Hsinchu | | 5 | Bell | 16 | Kaohsiung | | 6 | Dana | 19 | Hsinchu | | 1 | Hill | 21 | Kaohsiung | | 3 | Arden | 32 | Taipei | | 2 | Bond | 34 | Taipei | +----+-------+------+-----------+
若要反向排序,可在 ORDER BY
條件後方加上 DESC
:
-- 以 age 反向排序 SELECT * FROM persons ORDER BY age DESC;
+----+-------+------+-----------+ | id | name | age | city | +----+-------+------+-----------+ | 2 | Bond | 34 | Taipei | | 3 | Arden | 32 | Taipei | | 1 | Hill | 21 | Kaohsiung | | 6 | Dana | 19 | Hsinchu | | 5 | Bell | 16 | Kaohsiung | | 4 | Cole | 12 | Hsinchu | +----+-------+------+-----------+
若想要依照多個條件進行排序,可以用逗號分隔各個條件,排在前面的條件會被優先使用,例如先以 city
反向排序,再以 age
正向排序:
-- 先以 city 反向排序,再以 age 正向排序 SELECT * FROM persons ORDER BY city DESC, age;
+----+-------+------+-----------+ | id | name | age | city | +----+-------+------+-----------+ | 5 | Bell | 16 | Kaohsiung | | 1 | Hill | 21 | Kaohsiung | | 4 | Cole | 12 | Hsinchu | | 6 | Dana | 19 | Hsinchu | | 3 | Arden | 32 | Taipei | | 2 | Bond | 34 | Taipei | +----+-------+------+-----------+
當我們根據 ENUM
的資料進行排序時,會以該 ENUM
欄位定義時的順序為準,如果想要改變這個順序,可以使用 FIELD
自訂元素的順序:
-- 先以 city 自訂排序,再以 age 正向排序 SELECT * FROM persons ORDER BY FIELD(city, "Hsinchu", "Kaohsiung", "Taipei"), age;
+----+-------+------+-----------+ | id | name | age | city | +----+-------+------+-----------+ | 4 | Cole | 12 | Hsinchu | | 6 | Dana | 19 | Hsinchu | | 5 | Bell | 16 | Kaohsiung | | 1 | Hill | 21 | Kaohsiung | | 3 | Arden | 32 | Taipei | | 2 | Bond | 34 | Taipei | +----+-------+------+-----------+
參考資料:MySQL Tutorial