MySQL ORDER BY:用于SELECT和UPDATE的不同EXPLAIN

时间:2017-05-14 13:30:47

标签: mysql sql relational-database sql-order-by mariadb

请考虑包含queue_nameprioritymessage_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(使用相同的WHEREORDER 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

1 个答案:

答案 0 :(得分:0)

对于update,您需要第二个索引:

CREATE INDEX STATE_QUEUENAME_TIMESTAMP_2 ON `queue_messages` (queue_name, state, priority, message_timestamp);

您现有的索引不包含priority,因此无法用于order by