我正在编写一个批处理模式更新函数,目前它看起来像这样:
CREATE OR REPLACE FUNCTION gen_category_counts()
RETURNS VOID as $$
BEGIN
CREATE TEMPORARY TABLE category_stats ON COMMIT DROP AS
WITH
PC as(
SELECT category_id, COUNT(*)
FROM forum_posts fp
INNER JOIN forum_topics ft
ON ft.forum_id = fp.forum_id
AND ft.id = fp.topic_id
GROUP BY category_id
),
tc as(
SELECT category_id, COUNT(*)
FROM forum_topics
GROUP BY category_id
)
SELECT tc.category_id,tc.count AS topic_count, pc.count AS post_count
FROM tc,pc
WHERE tc.category_id = pc.category_id;
UPDATE forum_category_nodes fcn
set post_count = category_stats.post_count, topic_count = category_stats.topic_count
from category_stats
where fcn.id = category_stats.category_id;
END;
$$ LANGUAGE plpgsql;
是否有一些语法糖比写出一个完整的句子来声明一个仅在函数期间存在的临时表更好?
Sql Server 有一个select into #tablename
(不记得确切的语法,可能是@tablename)。我已经在邮件列表中看到了这种语法风格,但它在语法上是不正确的,EBBFselect into
文档也提到了临时表,以及紧挨着into
子句。
因此,如果 postgres 确实为隐式定义的作用域临时表提供了更好的糖,那是什么?:D
ps,我将编写具有数百行逻辑的程序,这些东西加起来:D