这是我的疑问:

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中 for each 不同的值保留一行,并像这样丢弃其他值:

 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给了我一个错误:

错误:"autor.entwickler"列必须出现在GROUP BY子句中

我完全理解这个错误,并假设mysql实现没有postgres实现那么符合SQL.但是我怎样才能得到想要的结果呢?

推荐答案

PostgreSQL目前不允许出现不明确的GROUP BY条语句,这些语句的结果取决于扫描表格的顺序、使用的计划等.这就是标准要求它可以正常工作的方式,但有些数据库(比如5.7之前的MySQL版本)允许更宽松的查询,只为SELECT列表中出现的元素 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;

(根据后续 comments 修改语法)

这有点像MySQL 5.7的ANY_VALUE(...) pseudo函数for group by,但与之相反,它表示distinct on子句中的值必须是唯一的,并且指定的not列可以接受任何值.

除非有ORDER BY,否则无法保证 Select 了哪些值.你通常应该有一个ORDER BY的可预测性.

还有人指出,使用min()max()这样的骨料也可以.虽然这是真的,并将导致可靠和可预测的结果,不像使用DISTINCT ON或模糊的GROUP BY,但由于需要额外的排序或聚合,它有性能成本,并且只适用于顺序数据类型.

Postgresql相关问答推荐

在SqlalChemy中转义动态CamelCase场

docker-compose.yml用于使用postgres的spring-boot应用程序

PostgreSQL 连接字符串的正则表达式

如何在docker-compose中使用docker secrets设置ConnectionString?

PG 16 的 AGE 安装抛出错误:无法创建 src/backend/parser/ag_scanner.c

Postgres 函数 now() 返回不正确的时区偏移量

使用 OpenCypher 和 Apache AGE 在两个顶点之间创建双向关系

函数将多列作为单列而不是多列返回

PostgreSQL 返回准确或最接近查询日期的日期

Windows PSQL 命令行: is there a way to allow for passwordless login?

如何向文本字段添加长度约束

mysql_insert_id 替代 postgresql

PostgreSQL CASE 在函数中的使用

PostgreSQL:使用 psql 命令行实用程序时 Windows 上的编码问题

在 PostgreSQL 中显示正在运行的查询的全文

用于更改 postgresql 用户密码的 bash 脚本

Rails:PG :: InsufficientPrivilege:错误:permission denied for relation schema_migrations

错误:prepared statement "S_1" already exists

Oracle 相当于 Postgres 的 DISTINCT ON?

删除空行