对于下面的查询,我只需要 Select 具有最低shape_type值(范围从1到10)的第一条记录.如果您知道如何使用postgresql轻松实现这一点,请提供帮助.谢谢你抽出时间.

select g.geo_id, gs.shape_type
from schema.geo g   
join schema.geo_shape gs on (g.geo_id=gs.geo_id)  
order by gs.shape_type asc;

推荐答案

PostgreSQL对于这种类型的查询有非常好的语法-distinct on:

在(表达式[,…]上) Select DISTINCT只保留第一排

所以你的问题变成:

select distinct on(g.geo_id)
    g.geo_id, gs.shape_type
from schema.geo g   
    join schema.geo_shape gs on (g.geo_id=gs.geo_id)  
order by g.geo_id, gs.shape_type asc;

一般来说,ANSI-SQL语法(在任何带有窗口函数和公共表表达式的RDBMS中,可以切换到子查询)是:

with cte as (
    select
        row_number() over(partition by g.geo_id order by gs.shape_type) as rn,
        g.geo_id, gs.shape_type
    from schema.geo g   
        join schema.geo_shape gs on (g.geo_id=gs.geo_id)  
)
select
    geo_id, shape_type
from cte
where rn = 1

Postgresql相关问答推荐

在Docker Compose中获取CSV文件数据?

包含JSONB属性的过滤器的索引策略

正在应用序列化迁移,但数据库没有更改

Postgres从spark触发post-write

PostgreSQL:动态SELECT查询

无法从外部连接到在 AWS EC2 实例上运行的 Postgres

无法从 docker-compose 上的其他服务解析 postgres 主机名

并行取消嵌套多个数组

如何从 .sql postgresql 备份恢复单个表?

try 访问本地主机中的数据库时如何解决Error: The server does not support SSL connections?

保存 geodjango PointField 时出错

postgreSQL 将列数据类型更改为没有时区的时间戳

将 SELECT 结果作为参数传递给 postgreSQL 函数

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

在 Windows 10 中执行时,Docker 容器关闭并给出data directory has wrong ownership错误

Postgis 中 2 点之间的距离,单位为 4326 米

在 PostgreSQL 中将列数据类型从 Text 更改为 Integer

Django:按月查询组

用于将布尔列排序为 true、null、false 的 SQL

如何获取一个月的天数?