【问题标题】:What is the best index for INNER JOINs having a WHERE and an ORDER BY clause?具有 WHERE 和 ORDER BY 子句的 INNER JOIN 的最佳索引是什么?
【发布时间】:2016-04-11 10:41:44
【问题描述】:

我正在使用 MySQL 和 InnoDB。 假设我有以下查询:

SELECT id FROM
Foo
INNER JOIN
Bar
ON Foo.id = Bar.fooId
WHERE Foo.column1 = N
ORDER BY Foo.column2 DESC LIMIT 100

这里,Foo.id 是主键,Bar.fooId 是 FK。

我应该添加到FooBar 表的最佳索引是什么?

目前我在Foo 表中的(Foo.column1, Foo.column2) 上有一个索引。我是否也应该将Foo.id 添加到此复合索引中?顺序是什么?

我找不到任何正式的参考来涵盖这个主题。

【问题讨论】:

  • 希望 Foo.id 是主键 & Bar.fooId 是外键。对吗?
  • @DipanwitaKundu 是的。已编辑。
  • 不需要添加 foo.id 作为复合索引,就足够了。
  • 选择的idFoo.id还是Bar.id
  • 视情况而定。那个SELECT 的答案对于另一个SELECT 不一定是“正确的”。 More tips.

标签: mysql indexing inner-join where-clause


【解决方案1】:

(Foo.column1, Foo.column2) 对于Foo 应该足够了,您不需要将 PK 添加到末尾,因为 innodb 总是在每个索引的末尾都有 PK。 Bar 需要在 fooId 上有一个索引。

运行explain <query> 来检查 MySQL 正在做什么。

对于Foo,您应该在不带using filesort 和100 行的额外中输入refusing index

Bar 应该在额外的类型中有 refusing index

【讨论】:

    猜你喜欢
    • 2018-08-18
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    • 2017-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多