Mysql - 范围查询和排序

时间:2012-08-29 07:38:55

标签: mysql

对于下一个查询:

SELECT m.id, m.body, m.poster, m.added 
   FROM messages m
   WHERE  ((m.poster_id = '11' OR m.poster_id = '22') AND (m.to = '11' OR m.to = '22'))
   ORDER BY m.id DESC
   LIMIT 10

什么是最好的指数?

我已经尝试过(poster_id,to,id) - 约1.5秒 尝试过(poster_id,to) - 约0,10s

如果我删除订单我得到0.00s

事情是,即使在空结果上,使用ORDER BY,我仍然可以得到0,09。

解释:

+----+-------------+-------+-------+------------------------------+-----------------+---------+------+------+-----------------------------+
| id | select_type | table | type  | possible_keys                | key             | key_len | ref  | rows | Extra                       |
+----+-------------+-------+-------+------------------------------+-----------------+---------+------+------+-----------------------------+
|  1 | SIMPLE      | m     | range | posterid_to_idx,to,poster_id | posterid_to_idx | 8       | NULL |    4 | Using where; Using filesort |
+----+-------------+-------+-------+------------------------------+-----------------+---------+------+------+-----------------------------+

由于

2 个答案:

答案 0 :(得分:0)

尝试简化您的查询,

SELECT m.id, m.body, m.poster, m.added 
FROM messages m
WHERE  m.poster_id IN ('11', '22') AND 
       m.to = IN ('11', '22')
ORDER BY m.id DESC
LIMIT 10

m.id单独),m.poster_idm.to

上添加索引

答案 1 :(得分:0)

您可能需要使用IN子句重写您的查询:

SELECT m.id, m.body, m.poster, m.added 
FROM messages m
WHERE  m.poster_id IN(11, 22) AND 
        m.to IN(11, 22)
ORDER BY m.id DESC
LIMIT 10;

添加以下Covering Index以获得最佳效果:

ALTER TABLE messages  ADD KEY ix1(poster_id, to, id, body, poster, added)

对于快速插入,您可以尝试正常索引:

ALTER TABLE messages  ADD KEY ix1(poster_id, to, id);