请考虑包含queue_name
,priority
和message_timestamp
列的表格。
这是一个复合索引:
CREATE INDEX STATE_QUEUENAME_PRIORITY_TIMESTAMP ON
`queue_messages` (queue_name, state, priority, message_timestamp);
EXPLAIN for SELECT:
EXPLAIN SELECT message_timestamp
from queue_messages
WHERE queue_name = 'folder'
AND state = 0
ORDER BY priority DESC, message_timestamp DESC
LIMIT 1;
返回Using where; Using index
EXPLAIN for UPDATE(使用相同的WHERE
和ORDER BY
!):
EXPLAIN UPDATE queue_messages
SET state = 1
WHERE queue_name = 'folder'
AND state = 0
ORDER BY priority DESC, message_timestamp DESC
LIMIT 1;
返回Using where; Using filesort
-
它会对性能产生重大影响(对于50k行,20ms SELECT与90ms UPDATE相比)。
如何强制MariaDB(MySQL)在UPDATE语句中删除filesort
?
答案 0 :(得分:0)
对于update
,您需要第二个索引:
CREATE INDEX STATE_QUEUENAME_TIMESTAMP_2 ON `queue_messages` (queue_name, state, priority, message_timestamp);
您现有的索引不包含priority
,因此无法用于order by
。