我有一个包含 1m 条记录的用户表:
User (id, fname, lname, deleted_at, guest)
我有以下针对 postgres 9.1 db 运行的查询:
SELECT "users".*
FROM "users"
WHERE (users.deleted_at IS NULL) AND (SUBSTRING(lower(fname), 1, 1) = 's')
ORDER BY guest = false, fname ASC
LIMIT 25 OFFSET 0
使用 pgAdmin 3,此 SQL 需要7120 毫秒才能返回 25 行。如果我删除 'ORDER BY guest = false, fname ASC' 查询只需31ms。
我有以下索引:
add_index "users", ["fname"], :name => "index_users_on_fname"
add_index "users", ["guest", "fname"], :name => "index_users_on_guest_and_fname"
add_index "users", ["deleted_at"], :name => "index_users_on_deleted_at"
add_index "users", ["guest"], :name => "index_users_on_guest"
有任何想法吗?谢谢!
更新解释
"Limit (cost=43541.55..43541.62 rows=25 width=1612) (actual time=1276.777..1276.783 rows=25 loops=1)"
" -> Sort (cost=43541.55..43558.82 rows=6905 width=1612) (actual time=1276.775..1276.777 rows=25 loops=1)"
" Sort Key: ((NOT guest)), fname"
" Sort Method: top-N heapsort Memory: 37kB"
" -> Seq Scan on users (cost=0.00..43346.70 rows=6905 width=1612) (actual time=5.143..1272.563 rows=475 loops=1)"
" Filter: ((deleted_at IS NULL) AND pubic_profile_visible AND ((fname)::text ~~ 's%'::text))"
"Total runtime: 1276.967 ms"