mysql - 添加平庸的连接后,查询时间从 7 秒减至 40 秒,我是否遗漏了什么?

标签 mysql join optimization

如果这个问题很愚蠢,请提前道歉。

所以我有一个大表,其中包含调查结果:

表调查(1.2 亿行):
积分 (tinyint(1))
问题(varchar(13))
CityID (smallint(3)) 索引
PersonID (varchar(13))
自动增量 (int(7)) PK

然后我有一个更小的查找表:

表 city_lookup(<1000 行)
CityID (smallint(3)) PK
城市 (varchar(13))

如果我这样做:

select sum(Points), CityID
from Survey
where CityID = 256
group by CityID

查询返回1行,耗时7秒

但如果我这样做:

select sum(Points), City
from Survey
inner join city_lookup on Survey.CityID = city_lookup.CityID
where Survey.CityID = 256
group by City

然后查询仍返回 1 行,需要 40 秒。

我知道,如果我调整查询,使连接仅在聚合查询运行后发生,即将主查询放入子查询中,那么它会将其缩短至 7 秒...但我是否应该这样做这样做,还是我错过了一些明显的优化步骤?

最佳答案

DBMS 在聚合之前可能会连接 1.2 亿行。我建议你先聚合然后加入:

select c.city, s.sum_points
from city_lookup c
join
(
  select sum(Points) as sum_points, CityID
  from Survey
  where CityID = 256
  group by CityID
) s on s.cityid = c.cityid;

我将为此创建以下索引:

CREATE idx ON survey(cityid, points);

关于mysql - 添加平庸的连接后,查询时间从 7 秒减至 40 秒,我是否遗漏了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44583585/

相关文章:

c# - 流畅的 NHibernate : Getting a "could not initialize collection" error while debugging an NUnit test in SharpDevelop

MySQL column = 0 返回 true

MySQL错误: The used SELECT statements have a different number of columns

c++ - 如何使这个颜色百分比函数更快? C++

使用子查询时的 MySQL 分组

mysql - 脚本在执行需要很长时间的查询后挂起

java - Hibernate Criteria 多表

mysql - 2 表连接和 1 组连接

java - 确定输入字符串是否为回文的有效方法

c# - 推荐的 ILNumerics 优化包