作者adrianshum (Alien)
看板Database
标题Re: [请益] Order by 和使用 Index 在效能上的关系
时间Fri Sep 4 16:38:47 2009
※ 引述《Per4 (Russell)》之铭言:
: 我使用的 DB 是 PostgreSQL,不过我想我的这个问题应该是相通的。
: 我的问题我想应该非常基本,但在网路上找的说法我都不太确定 ORDER BY「实际上」是
: 怎麽做的,所以请问大家。
: 问题起源很常见,基本上就是在论坛中列出论譠文章,
: 都是指定 forum_id 的情况下,Sort timestamp。
: 所以基本语法都是:
: SELECT * FROM messages WHERE forum_id = x ORDER BY timestamp DESC;
: 但是因为 Sort (ORDER BY) 基本原因都是要整张 table 扫过一遍才会知道顺序 O(N),
: 所以原则上会对 timestmap 作 INDEX(或类似作法),就会有 O(logN) 的 sort 效能。
: ( Reference:http://www.postgresql.org/docs/8.3/static/indexes-ordering.html )
: 而我想问的是,要达到 WHERE forum_id = x 同时 ORDER BY timestmap 的 logN效能,
: 是要 Index on (forum_id, timestmap),还是 Index on (timestamp) 就可以了?
: 或者都不是,是其他写法?
: 还请各位解惑。谢谢。
肯定是 index on timestamp 才有效.
要是你说的是 index on timestamp, blablabla_id
还可能会有效.
还要留心 index 的类型是什麽.
不少 DBMS 有分 hash index 和 b-tree index
前者在 order 的时候没有帮助, 因为 order
需要的是比较大小, b-tree 类的 index 才能
帮忙做排序.
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 202.155.236.82
※ 编辑: adrianshum 来自: 202.155.236.82 (09/04 16:39)