数据库
首页 > 数据库> > mysql – SQL排序不遵循group by语句,总是使用主键

mysql – SQL排序不遵循group by语句,总是使用主键

作者:互联网

我有一个SQL数据库,其中包含一个名为staff的表,其中包含以下列:

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

我应该找到每个部门薪水最高的工人,并使用以下声明:

select staff.workerID, staff.name, staff.department, max(staff.salary) AS biggest
from staff
group by staff.department

我从每个部门得到一名工人,但他们不是工资最高的工人,但是显示最大的工资值,即使工人没有得到那份工资.

显示的人是每个部门具有“最低”工人ID的工人.

因此,使用主键进行一些排序,即使在group by语句中没有提到它.

有人可以解释,发生了什么,也许可以正确排序.

解决方法:

对正在发生的事情的解释:

您正在staff.department上执行GROUP BY,但您的SELECT列表包含2个非分组列staff.workerID,staff.name.在标准的sql中,这是一个语法错误,但是MySql允许它,因此查询编写者必须确保它们自己处理这种情况.

参考: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.

从MySQL 5.1开始,可以通过在sql_mode中设置ONLY_FULL_GROUP_BY标志来禁用非标准功能:http://dev.mysql.com/doc/refman/5.6/en/sql-mode.html#sqlmode_only_full_group_by

怎么修:

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

在内部查询中,使用GROUP BY获取部门及其最高薪水.然后在外部查询中将这些结果与主表结合起来,这将为您提供所需的结果.

标签:sql,sorting,mysql,select,greatest-n-per-group
来源: https://codeday.me/bug/20191008/1872654.html