MySQL 每组最大 N 查询挂起

标签 mysql greatest-n-per-group

我有一个包含 PredCustId、StartDT 和 EndDT 列的表。对于给定的 StartDT,可以有多个 PredCustId。看起来是这样的

enter image description here

对于每个唯一的 StartDT,我想检索具有最大 PredCustId 的行。我专门尝试实现 here 所示的左连接解决方​​案,但每次运行它时查询都会挂起,我不明白为什么。

这有效

SELECT a.*
  FROM PredCusts AS a
LEFT OUTER JOIN PredCusts AS b
  ON a.StartDT = b.StartDT;

但这挂起

SELECT a.*
  FROM PredCusts AS a
LEFT OUTER JOIN PredCusts AS b
  ON a.StartDT = b.StartDT AND a.PredCustsId < b.PredCustsId;
为什么?请注意,我使用的是 MySQL 5.7.21 和 MySQL Workbench 6.3。

编辑 我的表有大约 370,000 行。唯一的索引是主键 PredCustsId。

最佳答案

您可以在子查询上使用内部联接来获取最大值

select * from PredCusts p
inner join (
  select StartDT, max(PredCustId) max_precustid
  from PredCusts
  group by StartDT
) t on t.StartDT = p.StartDT and p.PredCustId = t.max_precustid

关于MySQL 每组最大 N 查询挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49222559/

相关文章:

MySQL 按顺序查找每组最近/最大记录

MySQL 插入后选择

mysql - 在 Rails 模型中使用范围收集 "private"帖子

mysql - MYSQL 聚合函数计数不正确

sql - 在时间间隔内选择第一行和最后一行

mysql - SQL 仅选择列上具有最大值的行

mysql 触发更新以填充另一个表

php - 是否可以在 wordpress 中将日期存储为 meta_key?

sql - 如何获取每个产品的最新文档?

MySQL 查询获取最新记录