我有以下查询:
select "houses"."id",
"houses"."uuid",
COUNT(1) OVER() as full_count from "houses"
CROSS JOIN LATERAL jsonb_array_elements(houses.types) house_types
inner join "hoods" on "hoods"."id" = "houses"."hood_id" and "hoods"."owner_id" = 2
inner join "groups" on "groups"."hood_id" = "hoods"."id" and "groups"."manager_id" = 54
where house_types->>'type' = 'big'
group by "houses"."id", "houses"."uuid"
order by lower(houses.name) asc
limit 20
哪位正确地给我提供了头类型为“ big”的前20栋房屋,这些房屋位于Hood_id为2且与之关联的管理者为54个房屋的房屋中。
现在,问题是,有时我会拥有名称相同的房屋,而我只想保留其中一间并除去其余的。例如:
如果我的房屋桌子如下:
id, types, name
1, [{ type: 'rating' }], 'white house'
2, [{ type: 'rating' }], 'white house'
3, [{ type: 'rating' }], 'red house'
我只会得到ID为1和3的行。
在PostgreSQL中做到这一点的一种好方法是,假设我既可以将偏移量和限制都应用于查询,又希望删除重复项。
答案 0 :(得分:1)
使用group by
代替distinct on
:
select distinct on (lower(h.name)) h.id, h.uuid
COUNT(*) OVER() as full_count
from houses h cross join lateral
jsonb_array_elements(h.types) ht inner join
"hoods" ho
on ho.id = h.hood_id and
ho.owner_id = 2 inner join
"groups" g
on g.hood_id = ho.id and
g.manager_id = 54
where house_types->>'type' = 'big'
order by lower(houses.name) asc
limit 20;
编辑:
select h.*, count(*) over () as full_count
from (select distinct on (lower(h.name)) h.id, h.uuid
from houses h cross join lateral
jsonb_array_elements(h.types) ht inner join
"hoods" ho
on ho.id = h.hood_id and
ho.owner_id = 2 inner join
"groups" g
on g.hood_id = ho.id and
g.manager_id = 54
where house_types->>'type' = 'big'
order by lower(houses.name) asc
) h
limit 20