GROUP BY having MAX date

后端 未结 4 993
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 19:01

I have problem when executing this code:

SELECT * FROM tblpm n 
WHERE date_updated=(SELECT MAX(date_updated) 
FROM tblpm GROUP BY control_number 
HAVING cont         


        
4条回答
  •  [愿得一人]
    2020-12-04 19:43

    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);
    

提交回复
热议问题