簡體   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