Mysql – How to use GROUP BY and result with highest id value

greatest-n-per-groupgroup byMySQL

I used the following query to get the result

SELECT  `subjects`.*,`staffs`.`name`
    FROM  `subjects`
    LEFT JOIN  `staffs`  ON `staffs`.`uid` = `subjects`.`teacher`
    LEFT JOIN  `subject_student_selective`
       ON  `subject_student_selective`.`course` = `subjects`.`classid`
      AND  `subject_student_selective`.`subject` = `subjects`.`subject`
      AND  `subject_student_selective`.`student` = '12947'
    WHERE  `subjects`.`classid` = '26'
      AND  `subjects`.`active` = '1'
      AND  (`subjects`.`type`='normal'
              OR  `subject_student_selective`.`id`>0
           )
    GROUP BY  `subjects`.`subject`
    ORDER BY  `subjects`.`sort_order` 

This gave the result but, I need to get the result with highest ID'ed Group By subject.

Best Answer

For the one row with the highest ID:

ORDER BY ID DESC LIMIT 1

For the "latest" information associated with each subject, the problem is considerably more complex. Search for "groupwise max". Here's one link: http://mysql.rjweb.org/doc.php/groupwise_max