CREATE TABLE `mysql_order_by_test` (
`uid` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(80) NOT NULL,
`sex` TINYINT(1) NOT NULL COMMENT '1=男, 2=女',
PRIMARY KEY (`uid`),
KEY `idx_uid` (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `mysql_order_by_test` (`name`, `sex`) VALUES
('張三', 1),
('李四', 2),
('王二麻子', 1);
SELECT * FROM mysql_order_by_test ORDER BY uid ASC;
| uid | name | sex |
|---|---|---|
| 1 | 張三 | 1 |
| 2 | 李四 | 2 |
| 3 | 王二麻子 | 1 |
SELECT * FROM mysql_order_by_test ORDER BY uid DESC;
| uid | name | sex |
|---|---|---|
| 3 | 王二麻子 | 1 |
| 2 | 李四 | 2 |
| 1 | 張三 | 1 |
新增測試資料:
INSERT INTO mysql_order_by_test (name, sex) VALUES
('陳五', 1), -- uid=4
('趙六', 2); -- uid=5
SELECT * FROM mysql_order_by_test ORDER BY sex ASC, uid DESC;
| uid | name | sex |
|---|---|---|
| 5 | 趙六 | 2 |
| 4 | 陳五 | 2 |
| 2 | 李四 | 2 |
| 3 | 王二麻子 | 1 |
| 1 | 張三 | 1 |
解析:先將 sex=2(女)排前,sex=1(男)排後;同性別內 uid 大的在前。
EXPLAIN SELECT * FROM mysql_order_by_test ORDER BY uid ASC;
-- Extra: 無 Using filesort,使用 idx_uid 索引順序掃描
EXPLAIN SELECT * FROM mysql_order_by_test ORDER BY sex ASC, uid DESC;
-- Extra: Using filesort(因 sex 非索引前導欄)
sex, uid 排序 → 建立複合索引 INDEX idx_sex_uid (sex, uid)。INDEX idx_sex_uid_desc (sex ASC, uid DESC) 完美匹配。ORDER BY 確保結果穩定(無 ORDER BY 時分頁結果不確定)。實際操作驗證排序邏輯,配合 EXPLAIN 觀察索引使用,是掌握 ORDER BY 的最快捷徑。