简体   繁体   English

MySQL GROUP BY,并测试分组项

[英]MySQL GROUP BY, and testing the grouped items

I've got a query like this: 我有这样的查询:

select a, b, c, group_concat(d separator ', ')
from t
group by a;

This seems to work just fine. 这似乎工作正常。 As I understand it (forgive me, I'm a MySQL rookie!), it's returning rows of: 据我了解(原谅,我是MySQL菜鸟!),它返回以下行:

  • each unique a value 每个独特a价值
  • for each a value, one b and c value 对于每个a值,一个bc
  • also for each a value, all the d values, concatenated into one string 同样对于每个a值,所有d值都连接成一个字符串

This is what I want, but I also want to check that for each a , the b and c are always the same, for all rows with that a value. 这就是我想要的,但我也想检查每个a中, bc都是一样的,对于所有的行a值。

My first thought is to compare: 我的第一个想法是比较:

select count(*) from t group by a, b, c;

with: 与:

select count(*) from t group by a;

and make sure they're equal. 并确保它们相等。 But I've not convinced myself that this is correct, and I certainly am not sure there isn't a better way. 但是我并没有说服自己这是正确的,而且我当然不确定是否有更好的方法。 Is there a SQL/MySQL idiom for this? 是否有SQL / MySQL习惯用法?

Thanks! 谢谢!

The issue with relying on MySQL's Hidden Columns functionality is spelled out in the documentation : 文档中阐明了依赖MySQL的“隐藏列”功能的问题:

When using this feature, all rows in each group should have the same values for the columns that are ommitted from the GROUP BY part. 使用此功能时,每个组中的所有行对于从GROUP BY部分中省略的列都应具有相同的值。 The server is free to return any value from the group, so the results are indeterminate unless all values are the same. 服务器可以自由地从组中返回任何值,因此除非所有值都相同,否则结果是不确定的。

Applied to your example, that means that the values for b and c are arbitrary -- the results can't be relied upon to consistently return the same value, and the likelihood of seeing the behavior increases with the number of possible values that b / c can return. 应用于您的示例,这意味着bc的值是任意的-无法依赖结果始终返回相同的值,并且看到行为的可能性随b /的可能值的数量而增加c可以返回。 So there's no a lot of value to compare to GROUP BY a and GROUP BY a, b, c ... 因此,与GROUP BY aGROUP BY a, b, c相比没有太多价值。

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

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