SQL sorting does not follow group by statement, always uses primary key

前端 未结 4 1049
清酒与你
清酒与你 2021-01-15 06:40

I have a SQL database with a table called staff, having following columns:

workerID (Prim.key), name, department, salary

I am

4条回答
  •  星月不相逢
    2021-01-15 07:10

    Explanation for what is going on:

    You are performing a GROUP BY on staff.department, however your SELECT list contains 2 non-grouping columns staff.workerID, staff.name. In standard sql this is a syntax error, however MySql allows it so the query writers have to make sure that they handle such situations themselves.

    Reference: http://dev.mysql.com/doc/refman/5.0/en/group-by-handling.html

    In standard SQL, a query that includes a GROUP BY clause cannot refer to nonaggregated columns in the select list that are not named in the GROUP BY clause.

    MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause.

    The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate.

    Starting with MySQL 5.1 the non-standard feature can be disabled by setting the ONLY_FULL_GROUP_BY flag in sql_mode: http://dev.mysql.com/doc/refman/5.6/en/sql-mode.html#sqlmode_only_full_group_by

    How to fix:

    select staff.workerID, staff.name, staff.department, staff.salary
    from staff
    join (
      select staff.department, max(staff.salary) AS biggest
      from staff
      group by staff.department
    ) t
    on t.department = staff.department and t.biggest = staff.salary
    

    In the inner query, fetch department and its highest salary using GROUP BY. Then in the outer query join those results with the main table which would give you the desired results.

提交回复
热议问题