关于数据库:mysql的” group by”子句不给出错误

Mysql 'group by' clause does not give error

我的表名称为\\'product \\',其中包含以下列。

1
2
3
4
1. id
2. name
3. description
4. Price

在执行以下SQL查询时,这不会给我一个错误。

1
select name, sum(Price) from product group by Description;

在PostgreSQL上运行此查询时,它给我错误。

根据\\'group by \\'子句,select子句中的列名称应为group by条件的一部分。

因此,根据条件,SQL查询名称应按条件成为组的一部分。


在MySQL中,可以通过ONLY_FULL_GROUP_BY sql模式设置来配置此行为:

Reject queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on (uniquely determined by) GROUP BY columns.

As of MySQL 5.7.5, the default SQL mode includes ONLY_FULL_GROUP_BY.
(Before 5.7.5, MySQL does not detect functional dependency and
ONLY_FULL_GROUP_BY is not enabled by default. For a description of
pre-5.7.5 behavior, see the MySQL 5.6 Reference Manual.)

在您的MySQL ONLY_FULL_GROUP_BY中,显然未设置sql模式。如果您希望MySQL拒绝查询,则需要启用此行为。实际上,我鼓励大家确保启用此sql模式-除非您真的知道自己在做什么。


您应该这样编写查询

您应该只按列名写组,并在选择列名中写聚合函数。

1
select Description, sum(Price) from product group by Description;

如果要获取名称,则应编写如下查询:

您应该在分组依据中添加名称。

1
select name, sum(Price) from product group by name,Description;

,如果您只想按"描述"分组,则可以编写如下查询。

1
select max(name), sum(Price) from product group by Description;

如果名称相同,则可以使用minmax函数获取名称,或直接按

添加组