如何优化这个选择

问题描述 投票:0回答:3
SELECT *
FROM   trips,
       dates
WHERE  places_number_on_flag > 0
       AND places_number > 0
       AND ( places_number - ( (SELECT Count(id)
                                FROM   resrv_customers
                                WHERE  trip = trips.id
                                       AND ow > 0)
                               + (SELECT Count(id)
                                  FROM   resrv_customers
                                  WHERE  trip = trips.id
                                         AND extra_seat = 1
                                         AND ow > 0) ) < 20 )
       AND dates.id = trips.trip_date
       AND dates.from_date > 2458553;  

它在大约一分钟和50秒后返回5行。

我希望它更快。

sql postgresql optimization
3个回答
2
投票

一个优化是仅运行子查询一次并使用条件聚合来计算席位:

SELECT *
FROM   trips
  JOIN dates on dates.id = trips.trip_date
WHERE  places_number_on_flag > 0
       AND places_number > 0
       AND ( places_number - ( (SELECT Count(id) + count(id) filter (where extra_seat = 1)
                                FROM   resrv_customers
                                WHERE  trip = trips.id
                                       AND ow > 0)) < 20 )
       AND dates.from_date > 2458553;  

请注意,我使用显式JOIN运算符替换了WHERE子句中的古老和脆弱的隐式连接。它对性能没有任何影响,它只是更好的编码风格。


0
投票

我们可以尝试使用resrv_customers表的连接重写您的查询,而不是使用昂贵的相关子查询:

WITH cte AS (
    SELECT
        trip,
        COUNT(CASE WHEN ow > 0 THEN 1 END) AS cnt1,
        COUNT(CASE WHEN extra_seat = 1 AND ow > 0 THEN 1 END) AS cnt2
    FROM resrv_customers
    GROUP BY trip
)

SELECT *
FROM trips t
INNER JOIN dates d
    ON t.trip_date = d.id
LEFT JOIN cte r
    ON r.trip = t.id
WHERE
    places_number > 0 AND
    places_number - (r.cnt1 + r.cnt2) < 20 AND
    d.from_date > 2458553;

在这里索引可能很棘手,因为你正在做一个SELECT *。要让Postgres使用任何索引,您可能需要进行大量的列覆盖,即创建大型索引。


0
投票

试试这个:

with rc_count as
(
    select trip, count(*) as ow_count, sum( (extra_seat = 1)::int ) as ow_count_with_extra_seat
    from resrv_customers
    where ow > 0
    group by trip    
)

SELECT *
FROM   trips
join   dates on dates.id = trips.trip_date
join   rc_count rc on trips.id = trip 
WHERE  places_number_on_flag > 0
       AND places_number > 0
       AND dates.from_date > 2458553
       and places_number - (ow_count + ow_count_with_extra_seat) < 20       
© www.soinside.com 2019 - 2024. All rights reserved.