MySQL GROUP BY + ORDER BY -> Sorting 失效

以前都是用 MyISAM Engine
常搭配 GROUP BYHAVING 撰寫 SQL
不過一直沒遇過這個問題
現在的資料庫 Engine 都是用 InnoDB 比較多
熊熊遇到 GROUP BY + ORDER BY
Sorting 失效的問題

查了一下 MySQL 5.0 Certification Study Guide,在 9.5.1 GROUP BY and Sorting 這節看到:
For database engines other than MySQL, GROUP BY might not sort rows.

後來複製了一樣的 schema 跟 data 到一個新建的 table
MySQL Engine 改用 MyISAM 測試
結果也是一樣的

剛剛想到 phpMyAdmin 的 Operations 中有個 Alter table order by 的功能
趕緊測試了一下,果然可以! :D

我的資料庫結構大致如下:
no, int(10), UNSIGNED
page_id, varchar(50)
revision, int(10), UNSIGNED

no, Primary Key
page_id, INDEX Key
page_id & revision, UNIQUE Key

原本用
SELECT * FROM `table` GROUP BY page_id ORDER BY revision DESC
出來的 revision 順序為 1、2
由於不方便使用 Distinct

後來加入
ALTER TABLE `test` ORDER BY `revision` DESC
revision 順序就變 2、1 了!


測試環境:


2008-01-03 PM 03:43 補充:
剛經測試,上面的 Alter table order by 方法只適合用於 MyISAM 格式
InnoDB 格式不適用.... ooxx

如有後續再陸續補上~

2008-01-04 PM 07:15 補充:
可以用 GROUP BY page_id DESC ORDER BY revision 的方式來替代
不過我始終覺得很納悶,雖然 GROUP BY 可以 sorting
但我要 sorting 的不是 GROUP BY 欄位阿…
可以就好了!

Comments

Popular posts from this blog

CentOS7 如何新增/移除 Rich Rule for firewalld

mac 安裝 mtr

Howto use Postman test Cors