对于下面的查询,我只需要 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;
对于下面的查询,我只需要 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