我能做些什么来加速这个查询(使用Postgres 9.3.4)。我正在寻找最大的版本,它是有向图的一部分(在这种情况下版本< = 300)。
WITH RECURSIVE r(depth, revision_id) AS (
SELECT count(1) AS depth, r.revision_id AS revision_id
FROM revision AS r
WHERE r.revision_id = 300
GROUP BY r.revision_id
UNION ALL
SELECT rev1.depth + 1, rev2.parent_revision_id AS parent_revision_id
FROM rev1, revision AS rev2
WHERE rev2.revision_id != 1 AND rev2.revision_id = rev1.revision_id
)
SELECT t1.id AS id, t1.value as value
FROM (
SELECT DISTINCT ON (t2.id) t2.id AS id, t2.rev_id AS rev_id
FROM product AS t2
WHERE t2.rev_id = (
SELECT max(rev_id)
FROM product
WHERE t2.id = product.id
AND EXISTS (
SELECT 1 FROM r
WHERE r.revision_id = product.rev_id
)
) AND t2.deleted = false
) AS t1
我尝试选择select rev_id from product INTERSECT select revision_id from r
的最大交点,但这比上面的exists
版本略慢。此外,我存储CTE的临时表没有带来任何改进。
上述查询包含以下记录:
revision
--------
revision_id, parent_revision_id
1 null
2 1
3 2
4 2
5 3
6 5
product
-------
id, rev_id, value
1 2 a
2 3 b
3 4 c
1 5 a2
1 6 a3
...
300 a256
结果
id, value
1 a256
2 b
(注意product.id=3
不是结果集的一部分,因为它不是版本300的后代)