【问题标题】:Group without join in mysql没有加入mysql的组
【发布时间】:2014-06-17 00:13:05
【问题描述】:

我有一个包含许多人的数据库。每个人都有四分之一的观察结果

`
+----+---------+--------+--------+
| az | quarter | imp    |year
+----+---------+--------+--------+
|  1 | 1.2012  |      6 |  2012  |
|  1 | 2.2012  |      5 |  2012  |
|  1 | 3.2012  |      5 |  2012  |
|  1 | 4.2012  |      5 |  2012  |
|  2 | 1.2012  |      3 |  2012  |
|  2 | 2.2012  |      3 |  2012  |
|  2 | 3.2012  |      4 |  2012  |
|  2 | 4.2012  |      3 |  2012  |
|....|  ....   |        |
+----+---------+--------+-------+
`

我需要创建一个包含每年季度总和的列

+----+---------+--------+--------+
| az | year    | imp    |imp.year
+----+---------+--------+--------+
|  1 |   2012  |      6 |  21    
|  1 |   2012  |      5 |  21
|  1 |   2012  |      5 |  21
|  1 |   2012  |      5 |  21
|  2 |   2012  |      3 |  13
|  2 |   2012  |      3 |  13
|  2 |   2012  |      4 |  13
|  2 |   2012  |      3 |  13
|....|  ....   |        |
+----+---------+--------+-------+

我用过

CREATE TABLE IMP_TOT_YEAR AS SELECT
az, year, SUM(imp) as imp.year,
FROM IMP_TOT
GROUP BY az,year;

然后

CREATE TABLE complete AS SELECT
a.*, b.imp.year,
FROM IMP_TOT as a
left join IMP_TOT_YEAR as b 
on a.az=b.az and a.anno=b.year ;

我有超过 10 个变量,比如 imp 和很多年,所以加入太慢了。 它的运行时间超过 2 小时。 我正在寻找一种没有加入的方法,例如:

if quarter=1.2012 then imp.year = imp in (actual_row+1)+imp in (actual_row+2)+imp in (actual_row+3)

else imp.year = imp.year in (actual_row -1)

所以我不需要执行子查询或加入。有可能吗?

【问题讨论】:

  • 为什么要在季度栏中重复年份?
  • 你的桌子有多大?
  • 您的桌子上有哪些索引?如果您在(az, year) 上有索引,则GROUP BY 应该很快。

标签: mysql join group-by mysql-workbench


【解决方案1】:

如果您将索引添加到IMP_TOT_YEARjoin 应该没问题:

create index IMP_TOT_YEAR_az_yr on IMP_TOT_YEAR(az, yr);

听起来你有很多数据,所以使用中间表可能会很快。

另一方面,如果您想在一个表中执行此操作,请确保您在 IMP_TOT(az, yr) 上有一个索引并尝试:

SELECT t.*,
       (SELECT SUM(imp) as imp.year,
        FROM IMP_TOT t2
        WHERE t2.az = t.az and t2.yr = t.yr
       ) as YearTot
FROM IMP_TOT;

【讨论】:

  • 我在 30 秒内做到了:create index IMP_TOT_YEAR_az_yr on IMP_TOT_year(az, year); create index IMP_TOT_az_Tr on IMP_TOT(az, quarter);。完成的!!!!我是 mysql 新手,不知道创建索引会使查询如此之快。每次创建新表时我都需要这样做吗?
  • @user3384159 。 . . MySQL 有很好的索引文档。你可以从这里开始:dev.mysql.com/doc/refman/5.7/en/optimization-indexes.html.
  • 现在我做了create index IMP_TOT_YEAR_az_yr on IMP_TOT_year(az, year); 更快,但如果我也做了create index IMP_TOT_az_yr on IMP_TOT(az, year); 会更快吗?
  • @user3384159 。 . .对于此查询,这两个索引应该非常相似。将imp 作为第三列添加到任一列应该会提供一些额外的提升。
猜你喜欢
  • 2021-12-26
  • 1970-01-01
  • 2018-12-03
  • 1970-01-01
  • 1970-01-01
  • 2016-06-21
  • 2021-12-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多