如何索引表字段

时间:2014-11-11 10:33:24

标签: mysql

我正在为邮件收件箱开发一个大表 像

这样的查询
  

解释SELECT * FROM messages where(receptor='x1@yahoo.com'和sender='x2@yahoo.com')或(sender ='x1@yahoo.com'和receptor='x2@yahoo.com ')由id desc LIMIT 10命令;

非常慢并导致挂起服务器 请让我知道如何索引此表或更改查询以避免此问题 感谢

表格结构

mysql> DESCRIBE messages;                  
+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | bigint(20)   | NO   | PRI | NULL    | auto_increment | 
| sender   | varchar(65)  | NO   | MUL | NULL    |                | 
| is_sdel  | tinyint(1)   | NO   |     | NULL    |                | 
| receptor | varchar(65)  | NO   | MUL | NULL    |                | 
| is_rdel  | tinyint(1)   | NO   |     | NULL    |                | 
| dtime    | varchar(100) | NO   | MUL | NULL    |                | 
| title    | longtext     | NO   |     | NULL    |                | 
| com      | longtext     | NO   |     | NULL    |                | 
| ipu      | varchar(15)  | NO   |     | NULL    |                | 
| flage    | tinyint(2)   | NO   |     | NULL    |                | 
| view     | tinyint(2)   | NO   | MUL | NULL    |                | 
+----------+--------------+------+-----+---------+----------------+
11 rows in set (0.00 sec)

解释命令结果

 explain SELECT * FROM messages where (receptor='x1@yahoo.com' and sender='x2@yahoo.com') or (sender='x1@yahoo.com' and receptor='x2@yahoo.com') order by id desc LIMIT 10;
+----+-------------+----------+-------+--------------------------------------------------------------------------------+--------------------+---------+------+------+-----------------------------+
| id | select_type | table    | type  | possible_keys                                                                  | key                | key_len | ref  | rows | Extra                       |
+----+-------------+----------+-------+--------------------------------------------------------------------------------+--------------------+---------+------+------+-----------------------------+
|  1 | SIMPLE      | messages | range | sender,receptor,receptor-id,receptor-view,sender-receptor-id,sender-is_sdel-id | sender-receptor-id | 134     | NULL |    4 | Using where; Using filesort | 
+----+-------------+----------+-------+--------------------------------------------------------------------------------+--------------------+---------+------+------+-----------------------------+
1 row in set (0.01 sec)

2 个答案:

答案 0 :(得分:0)

在WHERE列(受体,发件人)

上创建索引
CREATE UNIQUE INDEX sender_index
ON messages (sender)

CREATE UNIQUE INDEX recever_index
ON messages (recever)

答案 1 :(得分:0)

从评论中提交我的回答:

SELECT * FROM (
  SELECT * FROM messages
  WHERE (receptor='x1@yahoo.com' and sender='x2@yahoo.com')
    or (sender='x1@yahoo.com' and receptor='x2@yahoo.com')
) x
order by id desc
LIMIT 10;

您遇到的问题是排序非常大的桌子。此解决方案强制MySQL首先过滤掉内部查询中的消息,然后仅在外部查询中对这些消息进行排序。