0

I have a table with these fields: userid, logintime, birthdate
I need to get ALL users between birthdate X and Y ordered with the most recently logged in first.

SELECT * 
FROM table 
WHERE birtdate BETWEEN x AND Y 
ORDER BY logintime DESC

If I defined an index on just birtdate, mysql would use filesort to order the results which I would like to avoid (table is getting big, query is popular).
Defining an index (logintime, birthdate) doesn't make sense to me since logintime isn't even in the WHERE clause (I'm only restricting the result set by birthdate)

Any elegant solutions in mysql?

4

3 回答 3

1

添加索引birthdate,logintime应该可以改善您的查询,但它有其缺点。我相信logintime(顾名思义)经常变化,所以数据库引擎必须更新底层索引,这反过来会导致索引碎片。
如果您的查询具有足够的选择性并且使用了索引,我认为文件排序不会有大问题birthdate
此外,您可以尝试将查询放在存储过程的主体中;在这种情况下,与 ad-hoc 查询相比,mysql 将更有效地使用缓存。

于 2011-07-09T18:22:06.073 回答
0

The index have to be birtdate, longtime (first you have to satisfy the WHERE clause, then the order), but I'm not sure it can use index for sorting with between condition. How many records it needs to sort? As Query is popular, you can use memcache or another caching mechanism to serve the results without hitting the database

于 2011-07-09T17:44:48.120 回答
0

AFAIK,对列有索引对排序没有影响,仅对搜索有帮助 - 它有助于where子句,而不是order by子句。

编辑:关注@Darhazer 的链接 - 基本上是说“ORDER BY 可以通过索引来满足”

于 2011-07-09T19:35:25.890 回答