使用分组集时,PostgreSQL where子句未下推

时间:2018-10-30 14:14:27

标签: sql postgresql set grouping

SELECT *
FROM (
    SELECT SUM(quantity) AS quantity,
        product_location_id,
        location_bin_id,
        product_lot_id,
        product_serial_id,
        CASE
            WHEN GROUPING (product_location_id, location_bin_id, product_lot_id, product_serial_id) = 0 AND product_serial_id IS NOT NULL THEN
                'Serial'
            WHEN GROUPING (product_location_id, location_bin_id, product_lot_id, product_serial_id) = 0 THEN
                'Lot'
            ELSE
                'Quantity'
        END AS pick_by
    FROM product_location_bins
    WHERE status != 'Void'
        AND has_quantity = 'Yes'
    GROUP BY GROUPING SETS (
        (product_location_id, location_bin_id, product_lot_id, product_serial_id),
        (product_location_id, location_bin_id)
      )
    HAVING SUM(quantity) > 0
) x
WHERE x.product_serial_id = 5643

我有以上查询。使用普通的GROUP BY postgres可以“按下”外部where子句,并使用product_serial_id上的索引。当我使用分组集时,无法这样做。它解析整个内部查询,然后过滤结果。我想知道为什么会这样。分组集是否有限制?

1 个答案:

答案 0 :(得分:1)

您的查询很奇怪。您外部的where子句从grouping sets中消除了第二组结果,因为第二组的product_serial_id将是NULL。这将在外部where中过滤掉。

我认为您希望外部查询是这样的:

WHERE x.product_serial_id = 5643 OR x.product_serial_id IS NULL

我想Postgres可以为写得不好的代码增加优化-也就是说,省去了第二个grouping sets的工作,因为它被外部where过滤掉了。但是,通常这并不是优化的重点。