繁体   English   中英

postgres:选择外键计数少于值的行

[英]postgres: select rows where foreign key count less than value

我继承了一个执行速度特别慢的查询,但是尚不清楚维护该功能并降低查询成本的最佳途径。

查询的简化版本如下所示:

select * from api_event where COALESCE(
                (SELECT count(*) FROM api_ticket WHERE
                event_id = api_event.id),
                0
            ) < api_event.ticket_max AND COALESCE(
                (SELECT count(*) FROM api_ticket WHERE
                api_ticket.user_id = 45187 AND event_id = api_event.id
                and api_ticket.status != 'x'),
                0
            ) < api_event.ticket_max_per_user;

对它运行Explain / Analyze似乎告诉我,这需要对api_event表进行顺序扫描:

Seq Scan on api_event  (cost=0.00..69597.99 rows=448 width=243) (actual     time=0.059..230.981 rows=1351 loops=1)
Filter: ((COALESCE((SubPlan 1), 0::bigint) < ticket_max) AND     (COALESCE((SubPlan 2), 0::bigint) < ticket_max_per_user))
Rows Removed by Filter: 2647

关于如何改善这一点的任何建议?

将查询重写为显式join可能会有所帮助:

select e.*
from api_event e left join
     (select t.event_id, count(*) as cnt,
             sum(case when t.user_id = 45187 and t.status <> 'x' then 1 else 0 
                 end) as special_cnt
      from api_ticket t
      group by t.event_id
     ) t
     on e.id = t.event_id
where coalesce(t.cnt, 0) < e.ticket_max and
      coalesce(special_cnt, 0) < e.ticket_max_per_user;

这是一个杂乱的子查询,最近我通过避免使用杂乱的子查询with基于基础的查询一起使用来提高了某些查询的性能,这在Oracle中非常快,我希望它对Postgres有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM