ORM 框架生成 SQL 包含同一欄位重複排序:
SELECT `i`.*, `v`.`type`, `v`.`status`
FROM `V_STAT`.`unopen` AS `i`
LEFT JOIN `V_USER`.`info` AS `v` ON `i`.`uid` = `v`.`uid`
WHERE `i`.`uid` > 0 AND `i`.`corp` = '31' AND `i`.`doflag` = '2'
ORDER BY `uid` ASC, `uid` ASC, `corp` ASC
LIMIT 50;
執行時間 **2.5 秒**,EXPLAIN 顯示 Using filesort。
CREATE TABLE `unopen` (
`corp` tinyint(3) unsigned NOT NULL DEFAULT '0',
`invtype` tinyint(3) NOT NULL DEFAULT '1',
`uid` int(10) NOT NULL DEFAULT '0',
`username` char(32) NOT NULL DEFAULT '0',
`fatid` int(10) NOT NULL DEFAULT '0',
`fatname` char(32) NOT NULL DEFAULT '0',
`invtitle` char(100) NOT NULL DEFAULT '',
`invest` decimal(12,2) NOT NULL DEFAULT '0.00',
`opened` decimal(12,2) unsigned NOT NULL DEFAULT '0.00',
`unopened` decimal(12,2) NOT NULL DEFAULT '0.00',
`doflag` tinyint(3) NOT NULL DEFAULT '0',
`manual_opened` decimal(12,2) NOT NULL DEFAULT '0.00',
PRIMARY KEY (`uid`,`corp`,`doflag`,`invtype`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
主鍵 (uid, corp, doflag, invtype) 已涵蓋 WHERE 與 ORDER BY 所需欄位。
ORDER BY i.`uid` ASC, v.`uid` ASC, i.`corp` ASC
-- EXPLAIN: Using temporary; Using filesort
因 v.uid 來自右表,MySQL 需建立臨時表合併排序。
ORDER BY i.`uid` ASC, i.`corp` ASC
-- EXPLAIN: Using where (filesort 消失!)
-- 執行時間:毫秒級
(uid, corp, doflag, invtype) 依序滿足 WHERE uid>0 AND corp=31 AND doflag=2 的範圍掃描,且輸出順序天然符合 ORDER BY uid, corp,**無需額外排序**。filesort。v.uid)會強制建立 temporary table 合併排序,極大降低效能。ORDER BY 子句:同一欄位、同一方向只保留第一個。ORDER BY 欄位加上駕駛表別名(i.uid),避免歧義。EXPLAIN 確認 type=range/ref、key=PRIMARY、Extra 無 Using filesort/Using temporary。ORDER BY 欄位是否為驅動表索引前綴且順序一致。sort_buffer_size、max_length_for_sort_data、SQL_SMALL_RESULT。