我在订购两列时遇到了麻烦。
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表类型possible_keys键key_len ref行 额外1个SIMPLE文章ALL NULL NULL NULL NULL 437168使用 哪里;使用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),但只有当我尝试按一列排序时它才有效。
答案 0 :(得分:1)
让MySQL使用此查询的索引非常困难:
SELECT *
FROM articles
WHERE option <> 0 AND deleted = 0
ORDER BY date_added DESC
LIMIT 25 OFFSET 500
您可以尝试复合索引:articles(deleted, date_added, option)
。通过覆盖WHERE
和ORDER 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
。并且,最终排序不能保证在外部查询中浮出水面,但它确实在实践中起作用(并且由于实现而接近保证)。