简体   繁体   English

MySQL中的GROUP BY子句将具有不同值的记录分组

[英]GROUP BY clause in MySQL groups records with different values

MySQL GROUP BY clause groups records even when they have different values. MySQL GROUP BY子句对记录进行分组,即使它们具有不同的值也是如此。

However I would like it to as with DB2 SQL so that if records not contain exactly the same information they are not grouped. 但是,我希望它与DB2 SQL一样,以便如果记录不包含完全相同的信息,则不对它们进行分组。


Currently in MySQL for: 目前在MySQL中用于:

id Name ID名称

A Amanda 阿曼达

A Ana 安娜

the Group by id would return 1 record randomly (unless aggregation clauses used of course) Group by id将随机返回1条记录(当然,除非使用了聚合子句)

However in DB2 SQL the same Group by id would not group those: returning 2 records and never doing such a thing as picking randomly one of the values when grouping without using aggregation functions. 但是,在DB2 SQL中,相同的“ Group by id分组”不会将那些分组:返回2条记录,并且永远不会在分组时不使用聚合函数时随机选择一个值。

First, id is a bad name for a column that is not the primary key of a table. 首先,对于不是表主键的列, id是一个不好的名字。 But that is not relevant to your question. 但这与您的问题无关。

This query: 该查询:

select id, name
from t
group by id;

returns an error in almost any database other than MySQL. 在除MySQL之外的几乎所有数据库中返回错误。 The problem is that name is not in the group by and is not the argument of an aggregation function. 问题在于name不在group by ,也不是聚合函数的参数。 The failure is ANSI-standard behavior, not honored by MySQL. 失败是ANSI标准行为,MySQL不接受。

A typical way to write the query is: 编写查询的典型方法是:

select id, max(name)
from t
group by id;

This should work in all databases (assuming name is not some obscure type where max() doesn't work). 这应该适用于所有数据库(假设name不是max()无效的某种晦涩的类型)。

Or, if you want each name, then: 或者,如果您想要每个名字,那么:

select id, name
from t
group by id, name;

or the simpler: 或更简单:

select distinct id, name
from t;

In MySQL, you can get the ANSI standard behavior by setting ONLY_FULL_GROUP_BY for the database/session. 在MySQL中,您可以通过为数据库/会话设置ONLY_FULL_GROUP_BY来获得ANSI标准行为。 MySQL will then return an error, as DB2 does in this case. 然后,MySQL将返回错误,就像在这种情况下的DB2一样。

The most recent versions of MySQL have ONLY_FULL_GROUP_BY set by default. 默认情况下,最新版本的MySQL设置为ONLY_FULL_GROUP_BY

I do not think there is an automated way to do this but using 我认为没有自动方法可以执行此操作

GROUP BY id, name

Would give you the solution you are looking for 将为您提供所需的解决方案

Group by in mysql will group the records according to the set fields. mysql中的分组依据将根据设置的字段对记录进行分组。 Think of it as: It gets one and the others will not show up. 可以这样认为:它得到一个,其他的则不会出现。 It has uses, for example, to count how many times that ID is repeated on the table: 例如,它可以用来计算ID在表上重复的次数:

select count(id), id from table group by id

You can, however, to achieve your purpose, group by multiple fields, something among the lines of: 但是,可以实现您的目的,可以将多个字段进行分组,其中包括:

select * from table group by id, name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM