我的查询:
SELECT * FROM privatemessages69
WHERE sender='19' OR recipient='19'
ORDER BY id DESC;
我的表:
CREATE TABLE `privatemessages69` (
`id` int(11) NOT NULL auto_increment,
`recipient` int(11) NOT NULL,
`sender` int(11) NOT NULL,
`time` int(11) NOT NULL,
`readstatus` int(11) NOT NULL,
`message` varchar(255) NOT NULL,
`messagetype` int(11) NOT NULL,
`rdeleted` int(11) NOT NULL,
`sdeleted` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `msgpanel` (`sender`,`recipient`,`id`)
) ENGINE=InnoDB AUTO_INCREMENT=50000 DEFAULT CHARSET=latin1
解释:
mysql> explain SELECT * FROM privatemessages69 WHERE sender='19' OR recipient='19' ORDER BY id DESC;
+----+-------------+-------------------+-------+---------------+---------+---------+------+-------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------------------+-------+---------------+---------+---------+------+-------+-------------+
| 1 | SIMPLE | privatemessages69 | index | msgpanel | PRIMARY | 4 | NULL | 50191 | Using where |
+----+-------------+-------------------+-------+---------------+---------+---------+------+-------+-------------+
1 row in set (0.00 sec)
有人能告诉我为那个查询索引这个表的正确方法吗?如果我删除订单,则类型转到 ALL。
感谢您的帮助
最佳答案
在 sender
上有一个索引,在 recipient
上有一个索引对于这样的查询应该足够了:
CREATE INDEX ind_sender
ON privatemessages69 (sender) ;
CREATE INDEX ind_recipient
ON privatemessages69 (recipient) ;
而且我认为如果使用 UNION
编写它不会更快。
您也可以尝试添加这两个索引(并删除上面的索引):
CREATE INDEX ind_sender_2
ON privatemessages69 (sender, id) ;
CREATE INDEX ind_recipient_2
ON privatemessages69 (recipient, id) ;
我现在无法测试,但它可能会摆脱文件排序。
您仍然可以编辑您的问题并在末尾添加:
- 使用 ORDER BY 的时间:(3-4 秒 你说)
- 总行数 表:
- 行数
收件人=19
: - 行数
发件人=19
: - 查询的行数 返回:
我昨天对大约 30 万行进行的一些测试显示查询运行时间不到一秒。缓慢可能是由于 MySQL 的配置设置。
此外:无论您输入什么(而不是 19
),查询是否需要 3-4 秒?
关于mysql - 如何使用或使用多列为 mysql 查询建立索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5797319/