我有一个包含 PredCustId、StartDT 和 EndDT 列的表。对于给定的 StartDT,可以有多个 PredCustId。看起来是这样的
对于每个唯一的 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/