GROUP BY having MAX date GROUP BY having MAX date mysql mysql

GROUP BY having MAX date


Putting the subquery in the WHERE clause and restricting it to n.control_number means it runs the subquery many times. This is called a correlated subquery, and it's often a performance killer.

It's better to run the subquery once, in the FROM clause, to get the max date per control number.

SELECT n.* FROM tblpm n INNER JOIN (  SELECT control_number, MAX(date_updated) AS date_updated  FROM tblpm GROUP BY control_number) AS max USING (control_number, date_updated);


There's no need to group in that subquery... a where clause would suffice:

SELECT * FROM tblpm nWHERE date_updated=(SELECT MAX(date_updated)    FROM tblpm WHERE control_number=n.control_number)

Also, do you have an index on the 'date_updated' column? That would certainly help.


Another way that doesn't use group by:

SELECT * FROM tblpm n   WHERE date_updated=(SELECT date_updated FROM tblpm n                         ORDER BY date_updated desc LIMIT 1)