Mysql: 按两列排序,使用文件排序

Mysql: order by two column, use filesort

我无法订购两列。

EXPLAIN SELECT * FROM articles WHERE option <>0 AND deleted=0 ORDER BY
    date_added DESC, category_id DESC LIMIT 25 OFFSET 500

id select_type table type possible_keys key key_len ref rows Extra 1 SIMPLE articles ALL NULL NULL NULL NULL 437168 Using where; Using filesort

我为 (option, deleted, date_added, category_id)

添加单个索引

当我使用:

EXPLAIN SELECT * FROM articles WHERE option <>0 AND deleted=0 ORDER BY
    date_added DESC LIMIT 25 OFFSET 500

EXPLAIN SELECT * FROM articles WHERE option <>0 AND deleted=0 ORDER BY
    category_id DESC LIMIT 25 OFFSET 500

仅在

处使用

我尝试将索引添加到 (option, deleted, date_added, category_id) 但它仅在我尝试按一列排序时有效。

很难MySQL为这个查询使用索引:

SELECT *
FROM articles
WHERE option <> 0 AND deleted = 0
ORDER BY date_added DESC
LIMIT 25 OFFSET 500

你可以试试复合索引:articles(deleted, date_added, option)。通过覆盖 WHEREORDER BY,MySQL 可能 使用它。

如果您可以添加一个 optionflag 列用于相等性测试(而不是 <>),则将查询编写为:

SELECT *
FROM articles
WHERE optionflag = 1 AND deleted = 0
ORDER BY date_added DESC
LIMIT 25 OFFSET 500;

那么 articles(deleted, optionflag, date_added desc) 上的索引会很好用。

否则子查询可能适合您:

SELECT a.*
FROM (SELECT *
      FROM articles
      WHERE deleted = 0
      ORDER BY date_added DESC
     ) a
WHERE option <> 0
LIMIT 25 OFFSET 500;

这实现了中间结果,但它仍然在做 order by。并且,不能保证最终排序在外部查询中出现,但它在实践中确实有效(并且由于物化而接近保证)。