gpt4 book ai didi

mysql - 消除 PostgreSQL SELECT 语句中的重复行

转载 作者:IT老高 更新时间:2023-10-28 23:53:47 26 4
gpt4 key购买 nike

这是我的查询:

SELECT autor.entwickler,anwendung.name
FROM autor
left join anwendung
on anwendung.name = autor.anwendung;

entwickler | name
------------+-------------
Benutzer 1 | Anwendung 1
Benutzer 2 | Anwendung 1
Benutzer 2 | Anwendung 2
Benutzer 1 | Anwendung 3
Benutzer 1 | Anwendung 4
Benutzer 2 | Anwendung 4
(6 rows)

我想为字段 name 中的每个不同值保留一行,并像这样丢弃其他值:

 entwickler |    name     
------------+-------------
Benutzer 1 | Anwendung 1
Benutzer 2 | Anwendung 2
Benutzer 1 | Anwendung 3
Benutzer 1 | Anwendung 4

在 MySQL 中我会这样做:

SELECT autor.entwickler,anwendung.name
FROM autor
left join anwendung
on anwendung.name = autor.anwendung
GROUP BY anwendung.name;

但是 PostgreSQL 给了我这个错误:

ERROR: column "autor.entwickler" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT autor.entwickler FROM autor left join anwendung on an ...

我完全理解错误并假设 mysql 实现比 postgres 实现更不符合 SQL。但是我怎样才能得到想要的结果呢?

最佳答案

PostgreSQL 目前不允许模棱两可的 GROUP BY 语句,其中结果取决于扫描表的顺序、使用的计划等。这就是标准所说的它应该如何工作 AFAIK,但是一些数据库(如 5.7 之前的 MySQL 版本)允许更宽松的查询,这些查询只选择出现在 SELECT 列表中但不在 GROUP BY 中的元素遇到的第一个值。

在 PostgreSQL 中,你应该使用 DISTINCT ON对于这种查询。

你想写这样的东西:

SELECT DISTINCT ON (anwendung.name) anwendung.name, autor.entwickler
FROM author
left join anwendung on anwendung.name = autor.anwendung;

(根据后续评论更正语法)

这有点像 MySQL 5.7 的 ANY_VALUE(...) 伪函数,用于 group by,但相反 - 它表示distinct on 子句必须是唯一的,对于指定的列,任何值都是可接受的。

除非有 ORDER BY,否则无法保证选择了哪些值。您通常应该有一个 ORDER BY 以实现可预测性。

还注意到使用像 min()max() 这样的聚合是可行的。虽然这是真的 - 并且会导致可靠和可预测的结果,与使用 DISTINCT ON 或模棱两可的 GROUP BY 不同 - 由于需要额外的排序,它会产生性能成本或聚合,它仅适用于序数数据类型。

关于mysql - 消除 PostgreSQL SELECT 语句中的重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8373087/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com