我在“tblmessages”中有 300,000 行,并且我正在尝试运行此查询。 如果你不使用“order by msgId desc”它运行得非常快,但是当我添加订单时它非常非常慢。
我错过了什么......?
SELECT msgId
FROM tblmessages
left join wp_users as a on a.ID = (CASE WHEN (msgFromUserId=1) then tblmessages.msgToUserId else tblmessages.msgFromUserId END)
left join tblforum_users u1 on u1.user_ID =(CASE WHEN (msgFromUserId=1) then tblmessages.msgToUserId else tblmessages.msgFromUserId END)
where (msgFromUserId=1 or msgToUserId=1)
order by msgId desc limit 0,20
解释后:
+----+-------------+-------------+------------+-------------+---------------------------------------+---------------------------------------+---------+------+--------+----------+-----------------------------------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------------+------------+-------------+---------------------------------------+---------------------------------------+---------+------+--------+----------+-----------------------------------------------------+
| 1 | SIMPLE | tblmessages | NULL | index_merge | IXtbl_messages_from,IX_tblmessages_to | IX_tblmessages_from,IX_tblmessages_to | 5,5 | NULL | 726454 | 100.00 | Using union(IX_tblmessages_from,IX_tblmessages_to); |
Using where; Using filesort |
| 1 | SIMPLE | a | NULL | eq_ref | PRIMARY | PRIMARY | 8 | func | 1 | 100.00 | Using where; Using index |
| 1 | SIMPLE | u1 | NULL | eq_ref | PRIMARY | PRIMARY | 4 | func | 1 | 100.00 | Using where; Using index |
+----+-------------+-------------+------------+-------------+---------------------------------------+---------------------------------------+---------+------+--------+----------+-----------------------------------------------------+
以及有关tblmessages
的更多信息:
Data 12.1 GiB
Index 190.8 MiB
Total 12.3 GiB
最佳答案
造成这种情况的原因有两个:
If U don't use "order by msgId desc" It's run very fast, but when I add the order It's very very slow.
第一个是您的查询末尾有一个“LIMIT 20”行。对此查询的结果进行排序(通过“order by”)将需要所有满足where子句的行被拉出/生成、排序等。为了得到正确的 20 行。
第二是有点主观,但我会说你的表没有必要的索引来支持该查询的优化。或者,从另一种角度来看,这样的查询通常会因为 IF-THEN 子句上的多个联接而运行缓慢。我对解决此问题的建议是将查询简化为多个查询,或者使用相关表的“SHOW CREATE TABLE”语句以及汇总索引、分区等的 INFORMATION_SCHEMA 查询之一来更新您的问题。从那里我们可能会更新设计(例如添加多列索引/索引/无论其拼写如何......)
关于mysql - 加快 MYSQL 具有 order by 的查询速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42932307/