MySQL 的 Index 設計技巧

Percona 的「Indexing 101: Optimizing MySQL queries on a single table」這篇講了最基本的 index 設計技巧,雖然文章裡沒提到,但最好是需要 B-treeB+ tree 的背景知識。

MySQL 的 query 大致分成幾個階段。先決定要使用哪些 index (或是完全不用),然後透過 index 抓出符合條件資料 (或是 table scan),最後再細部過濾。

以文章裡提到的「Multiple inequalities」範例裡這樣的 SQL query 來討論:

SELECT * FROM t WHERE c > 100 and b < 10 and d = 'xyz'

如果 index 是 (d, c),需要在透過這組 index 抓出資料後再過濾 b < 10 的條件。而如果 index 是 (d, b),需要在取出資料後再過濾 c > 100 的條件。也就是 B+ tree 做不到的事情,就要另外 post-processing。

另外也有提到 covering index 對效能提昇的原理,不過這就有點屬於怪招了...

Leave a Reply

Your email address will not be published. Required fields are marked *