代码之家  ›  专栏  ›  技术社区  ›  hermit

PostgreSQL在select和group by中使用不同的列不会导致错误

  •  0
  • hermit  · 技术社区  · 2 年前

    所以,我了解到 windows函数 从这里开始, https://www.postgresqltutorial.com/postgresql-window-function/

    在开始窗口功能部分之前,请简要介绍 聚合函数 分组依据 条款

    以下是我根据教程使用的参考表:

    enter image description here enter image description here

    据我所知,一个人应该在 选择 分组依据 条款例如。

    SELECT p.group_id, avg(p.price)  from PRODUCTS p GROUP BY p.group_id;
    

    否则,PostgreSQL将给出一个错误: column "" must appear in the GROUP BY clause or be used in an aggregate function.

    但是,我对以下查询的结果有点困惑:

    select group_name,avg(price) from product_groups inner join products p using (group_id) group by group_id;

    首先,我在select和group中使用不同的列,即。 group_name group_id 分别地但是,它并没有抛出类似于上面的错误!

    并给出了以下结果。看起来像 组名称 group_id 在这里可以互换使用。有人能解释一下这里发生了什么吗?

    enter image description here

    1 回复  |  直到 2 年前
        1
  •  2
  •   Tim Biegeleisen    2 年前

    您对规则的理解 GROUP BY 几乎 完成通常 SELECT 子句也必须出现在 分组依据 然而,ANSI标准中有一个例外,它规定如果 分组依据 哪一个 独特地 确定其他列的值,则这些其他列也可以出现在 选择 条款

    仔细查看您的第二个查询:

    SELECT group_name, AVG(price)           -- valid, because if we know
    FROM product_groups                     -- group_id then we also know
    INNER JOIN products p USING (group_id)  -- group_name
    GROUP BY group_id;
    

    products 表,如果 group_id 要么是主键,要么是唯一键,那么如果我们为 group_id ,我们也知道 group_name 如果是的话,那么从技术上讲,您的第二个查询是符合ANSI的。与大多数其他数据库相比,Postgres更倾向于严格遵循ANSI标准,因此它接受您的查询是有效的。