0

对于下一个查询:

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.5s 试过 (poster_id, to) - 大约 0,10s

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

问题是即使在空结果上,使用 ORDER BY,我仍然得到 0,09s。

解释:

+----+-------------+-------+-------+------------------------------+-----------------+---------+------+------+-----------------------------+
| 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 |
+----+-------------+-------+-------+------------------------------+-----------------+---------+------+------+-----------------------------+

谢谢

4

2 回答 2

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_id和上添加索引m.to

于 2012-08-29T07:43:41.387 回答
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;

添加以下覆盖指数以获得最佳性能:

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

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

ALTER TABLE messages  ADD KEY ix1(poster_id, to, id);
于 2012-08-29T07:44:14.847 回答