的PostgreSQL有這種類型的查詢非常漂亮的語法 - distinct on:
SELECT DISTINCT ON(表達式[,...])只保留的 第一行各自組行的地方給定的表達式評估爲相等。使用與 ORDER BY(見上)相同的規則解釋DISTINCT ON表達式。請注意,除非使用ORDER BY來確保首先出現所需的行 ,否則每組的「第一行」爲 不可預知。
所以您的查詢就會變成:
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