简体   繁体   中英

How can I make this query run faster?

I'm just wondering if theres anything I could do to make the query run a bit faster?

I have this query:

SELECT * FROM posts
WHERE posts.exists = 'n'
ORDER BY posts.ratecount DESC
LIMIT 0,100

Takes: 2.47s @ 0,100 | 6.18s @ 500,100

This works but it tends to get rather slow as the limit increases (100,100 > 200,100 etc).

Using an index doesn't seem to help either:

SELECT * FROM posts
USE INDEX(ratecount_ca)
WHERE posts.exists = 'n'
ORDER BY posts.ratecount DESC
LIMIT 0,100

Takes: 8.59s @ 0,100 | 28.98s @ 500,100

Strangely enough, without the WHERE it works perfect.

A descending index would most likely fix the issue but since that doesn't seem to be implemented yet, I need another option. Doing the WHERE after it's ordered would mostly likely speed it up too, but since I'm rather new to SQL I have no idea how to do :<

What version of MySQL are you using? v5.0 docs suggest there is a way to change index order.

I would suggest to create index on both columns. It should look something like:

CREATE INDEX index_2_cols ON posts(exists, ratecount DESC);

既然您说省略where条件使其运行起来很快,那么我将尝试在posts表的exists字段上创建索引

CREATE INDEX ON posts_exists ON posts (exists(10));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM