gpt4 book ai didi

postgresql - Postgres : The best way to optmize "greater than" query

转载 作者:行者123 更新时间:2023-11-29 13:30:54 24 4
gpt4 key购买 nike

优化在子组的下一个 id 值上与同一张表连接的连接查询的最佳方法是什么?现在我有这样的东西:

CREATE OR REPLACE FUNCTION select_next_id(bigint, bigint) RETURNS bigint AS $body$
DECLARE
_id bigint;
BEGIN
SELECT id INTO _id FROM table WHERE id_group = $2 AND id > $1 ORDER BY id ASC LIMIT 1;
RETURN _id;
END;
$body$ LANGUAGE plpgsql;

和 JOIN 查询:

SELECT * FROM table t1
JOIN table t2 ON t2.id = select_next_id(t1.id, t1.id_group)

该表有超过 2kk 行,并且需要非常非常长的时间。有没有更好的方法来快速做到这一点?我在列 id 上也有 UNIQUE INDEX。我猜不是很有帮助。

一些示例数据:

id | id_group=============1  | 12  | 13  | 14  | 25  | 26  | 220 | 425 | 437 | 440 | 155 | 2

我想收到这样的东西:

id | id_next1  | 22  | 33  | null4  | 5 5  | 66  | 55

等等。

最佳答案

对于函数中的查询,您需要(id_group, id) 上的索引,而不仅仅是(id)

接下来,你不需要plpgsql在函数本身的开销,你可以通过使其稳定且具有较小的成本来给planner一些提示:

CREATE OR REPLACE FUNCTION select_next_id(bigint, bigint) RETURNS bigint AS $body$
SELECT id FROM table WHERE id_group = $2 AND id > $1 ORDER BY id ASC LIMIT 1;
$body$ LANGUAGE sql STABLE COST 10;

在最后的查询中,根据您实际尝试执行的操作,您可以使用 lead() 摆脱连接和函数调用,如 horse 所强调的那样:

http://www.postgresql.org/docs/current/static/tutorial-window.html

关于postgresql - Postgres : The best way to optmize "greater than" query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23778221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com