MySQL 违反了 SQL 标准
MySQL violating SQL standard
在 this article 关于 ANSI SQL 99 standard requirement group by
他们说:
the statement’s select list may consist only of references to Columns that are single-valued per group – this means that the select list can’t include a reference to an interim result Column that isn’t also included in the GROUP BY clause
但是在MySQL中我们可以这样做:
select b
from a
group by c
而且它没有抱怨,所以我想知道这是否被视为违反标准。
我已经读过 this answer 关于这个话题,但我想知道这是否违规,或者可以被视为违规(假设有一个例子说 "be strictly to the SQL standard" 结果是我写的),而不是它为什么有效或其他原因。
原来是我理解错了
MySQL 不再支持:
select b
from a
group by c;
(至少使用默认设置)。耶!这个 returns 一个错误,就像它在几乎所有其他数据库中应该发生的那样(我认为 SQLite 可能是现在最后的坚持)。
这违反了一般标准(见下文)。问题是每个 c
值返回一行。 GROUP BY
中除 c
之外的任何内容都应该是 GROUP BY
.
的参数
有一种情况是允许的。即 c
是 a
中的主键或唯一键(技术上称为 "functionally dependent")。在这种情况下,您可以 select 来自 table 的其他列而无需聚合函数。 Postgres 是支持此功能的数据库之一。
如果你想要每个 c
的一个值 b
,那么规范的解决方案是这样的:
select max(b)
from a
group by c;
Postgres 还提供 distinct on
以提供更大的灵活性:
select distinct on (c) b
from a
order by c, random();
在 this article 关于 ANSI SQL 99 standard requirement group by
他们说:
the statement’s select list may consist only of references to Columns that are single-valued per group – this means that the select list can’t include a reference to an interim result Column that isn’t also included in the GROUP BY clause
但是在MySQL中我们可以这样做:
select b
from a
group by c
而且它没有抱怨,所以我想知道这是否被视为违反标准。
我已经读过 this answer 关于这个话题,但我想知道这是否违规,或者可以被视为违规(假设有一个例子说 "be strictly to the SQL standard" 结果是我写的),而不是它为什么有效或其他原因。
原来是我理解错了
MySQL 不再支持:
select b
from a
group by c;
(至少使用默认设置)。耶!这个 returns 一个错误,就像它在几乎所有其他数据库中应该发生的那样(我认为 SQLite 可能是现在最后的坚持)。
这违反了一般标准(见下文)。问题是每个 c
值返回一行。 GROUP BY
中除 c
之外的任何内容都应该是 GROUP BY
.
有一种情况是允许的。即 c
是 a
中的主键或唯一键(技术上称为 "functionally dependent")。在这种情况下,您可以 select 来自 table 的其他列而无需聚合函数。 Postgres 是支持此功能的数据库之一。
如果你想要每个 c
的一个值 b
,那么规范的解决方案是这样的:
select max(b)
from a
group by c;
Postgres 还提供 distinct on
以提供更大的灵活性:
select distinct on (c) b
from a
order by c, random();