【问题标题】:mysql multiple joins with conditions on multiple table query performancemysql 多个连接条件对多表查询性能的影响
【发布时间】:2012-03-28 16:20:22
【问题描述】:

假设表格:

主要(1M 行): id, a_id, b_id, c_id, d_id, 金额, 年份, main_col

a(500 行): id, a_col1, a_col2

b(2000 行): id, b_col1, b_col2, b_col3

c(500 行): id, c_col1, c_col2

d(1000 行): id, d_col1, d_col2

我们有这样的查询:

select sum(amounts), main_col 
   join a on a.id = main.a_id 
   join b on b.id = main.b_id 
   join c on c.id = main.c_id 
   join d on d.id = main.d_id 
   where a.a_col1 in (...) 
     and a.a_col2 in (..) 
     and b.b_col1 in (...) 
     and b.b_col2 in (...) 
     and b.b_col3 in (..) 
     and c.c_col1 in (..) 
     and c.c_col2 in (..) 
     and d.d_col1 in (..) 
     and d.d_col2 in (..)
     and year = 2011

   group by main.main_col

知道谁在主表上创建索引以提高查询性能吗?

谢谢

更新: 将索引添加到 a、b、c、d 表中,以使列显示在 where 我已经在主表(a_id、b_id、c_id、d_id、main_col)上尝试了多个列索引,它们比其他索引具有最佳性能,例如在 a_id、b_id... 上添加单个索引,但它仍然不够快满足要求, on query 将需要 7 秒来运行最大情况

【问题讨论】:

  • 如果您真的很难优化查询并且您已经尝试了所有方法,您可能需要查看您的架构。可能会去规范化/创建聚合表等以提高性能。

标签: mysql database performance


【解决方案1】:

在 main(id) 上创建索引 id_main

您可以在其他列上创建多个索引,看看它是如何为您工作的。

http://dev.mysql.com/doc/refman/5.0/en/create-index.html

【讨论】:

  • 默认添加主键(id)索引,我尝试为主表上的外键添加多个索引,并使用解释检查sql和mysql没有选择索引查询
  • 好的。你没有说你的表上有主键,我不想假设你有,而只是如何应用索引。 MySQL 引擎将根据它认为最好的方式选择要遵循的索引/执行路径。您可以阅读这篇关于如何调整查询性能的文章:databasejournal.com/features/mysql/article.php/1382791/…
【解决方案2】:

这实际上取决于每个连接的选择性、每个表的大小等细节。一般来说,在主表的外键上添加一个或多个索引可能是明智之举,但谁能说出来信息有限?

这也可能有助于了解您的查询是如何执行的——尝试查看 MySQL 的“解释”或“解释扩展”。

【讨论】:

    【解决方案3】:

    由于默认情况下主键已经被索引,因此无法通过添加更多索引来优化连接。这样就剩下你的 where 语句了。所以它可以帮助为 x.x_colN 列添加索引。

    【讨论】:

      【解决方案4】:

      我认为你的 group_by 也应该有一个索引

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-15
        • 2013-11-04
        • 2020-04-23
        • 1970-01-01
        • 1970-01-01
        • 2016-09-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多