A problem that I have faced with SQL many times is pre-ordering the GROUP BY clause.
When you GROUP BY, MySQL will return a set of records which I call "representing records". These records represent the group that is selected.
For example select "id from test group by class" will return one "representing record" per unique value of the "class" field. The problem with this is that you have no control over which record will represent the group.