问题
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