MySQL Greatest N Per Group Query Hangs

為{幸葍}努か 提交于 2019-12-11 15:37:34

问题


I have a table with columns PredCustId, StartDT and EndDT. For a given StartDT, there can be multiple PredCustIds. Here's what this looks like

For each unique StartDT, I would like to retrieve the row with the largest PredCustId. I am specifically trying to implement the left-join solution as seen here but the query hangs every time I run it and I don't understand why.

This works

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

but this hangs

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

Why? Note that I am using MySQL 5.7.21 and MySQL Workbench 6.3.

EDIT My table has ~370,000 rows. The only index is the Primary Key, PredCustsId.


回答1:


You could use a inner join on a subquery for max value

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


来源:https://stackoverflow.com/questions/49222559/mysql-greatest-n-per-group-query-hangs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!