我正在try Select 属于具有多个订单的行程的订单.

我try 了许多方法,但找不到如何获得性能良好的查询.

重现这里的问题的是设置(这里是100000行,但实际上要在db-fiddle上看到超时的行数超过1000000行).

Schema (PostgreSQL v14)

create table trips (id bigint primary key);
create table orders (id bigint primary key, trip_id bigint);
create index trips_idx on trips (id);
create index orders_idx on orders (id);
create index orders_trip_idx on orders (trip_id);

insert into trips (id) select seq from generate_series(1,100000) seq;
insert into orders (id, trip_id) select seq, floor(random() * 100000 + 1) from generate_series(1,100000) seq;

Query #1

explain analyze select orders.id
from orders
inner join trips on trips.id = orders.trip_id
inner join orders trips_orders on trips_orders.trip_id = trips.id
group by orders.id, trips.id
having count(trips_orders) > 1
limit 50
;

View on DB Fiddle

以下是pgimerard在真正的问题上给我的答案:

pgmustard

推荐答案

你真的需要在旅行中加入吗?你可以试一试

SELECT shared.id
FROM orders shared
WHERE EXISTS (SELECT * FROM orders other 
              WHERE other.trip_id = shared.trip_id
              AND other.id != shared.id
              )
;

将GROUP BY替换为散列联接,或者

SELECT unnest(array_agg(orders.id))
FROM orders
GROUP BY trip_id
HAVING count(*) > 1
;

希望Postgres只使用Trip_id索引.

Postgresql相关问答推荐

如何使用postgr sql regex删除重复项和inc表记录

端口5432失败:致命:数据库xxx&不存在.在PostgreSQL数据库中

Select 所有数组类型和维度

如何确定要与给定转储文件一起使用的pg_Restore版本?

在Power BI和Excel中将日期格式化为正确格式

使用doobie,如何将Scala case类映射到带有类型tstzmultirange的PostgreSQL列?

TimescaleDB 连续聚合:如何存储连续聚合结果

如何在 PSQL 中查找从另一个表继承的子表

postgresql 更新错误ERROR: invalid input syntax for type boolean:

在 Ubuntu 11.04 服务器中启用对 postgresql 的 PHP 支持

PostgreSQL 如何比 SQLite 更快地执行写入?

如何在可选参数上查询 postgres?

timezone date_trunc 函数

如何将1 天 01:30:00等间隔转换为25:30:00?

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

如何在 Postgresql 中正确使用 FETCH FIRST?

判断materialized视图的上次刷新时间

在 OS X 上使用 Postgres.app 时如何将 psql 放在路径上?

在 PostgreSQL 中使用 CASE 一次影响多个列

如何获取一个月的天数?