gpt4 book ai didi

mysql - 大表 SQL 中具有最大值的子查询

转载 作者:行者123 更新时间:2023-11-29 12:48:24 24 4
gpt4 key购买 nike

我正在尝试进行查询以获取某人最后一次工作经历的日期以及他们离开公司的日期(在某些情况下该值为空,因为该人仍在公司工作)。

我有类似的东西:

  SELECT r.idcurriculum, r.startdate, r.lastdate FROM (
SELECT idcurriculum, max(startdate) as startdate
FROM workexperience
GROUP BY idcurriculum) as s
INNER JOIN workexperience r on (r.idcurriculum = s.idcurriculum)

结构应该是这样的:

idcurriculum | startdate | lastdate

1234 | 2010-05-01| null
2532 | 2005-10-01| 2010-02-28
5234 | 2011-07-01| 2013-10-31
1025 | 2012-04-01| 2014-03-31

我尝试运行该查询,但我不得不停止它,因为它花费的时间太长。 workexperience 表的重量约为 20GB。不知道查询是否有错,我只运行了10分钟。

我们将非常感谢您的帮助。

最佳答案

您可以尝试将查询改写为:

select r.*
from workexperience we
where not exists (select 1
from workexperience we2
where we2.idcurriculum = we.idcurriculum and
we2.startdate > we.startdate
);

重要提示:出于性能原因,您需要 idcurriculum 上的复合索引, startdate :

create index idx_workexperience_idcurriculum_startdate on workexperience(idcurriculum, strtdate)

查询的逻辑是:“获取 workexperience 中的所有行,其中不存在具有更大 idcurriculum 的相同 startdate 的行”。这是“让我最大化”的一种奇特方式。

group by ,MySQL 必须进行聚合,这通常涉及对数据进行排序——对于 20 GB 来说成本高昂。通过这个方法,可以通过索引来查找结果,速度应该会更快。

关于mysql - 大表 SQL 中具有最大值的子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25120074/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com