假设我在下面的(虚构)表中将消息存储在讨论板中,按主题组织,本身由整数标识:
CREATE TABLE MESSAGE(
message_global_id SERIAL PRIMARY KEY,
topic_id INTEGER DEFAULT 0,
message_nb_in_topic INTEGER,
text TEXT
);
我想将列message_nb_in_topic设置为序列的等效值,但是会为每个主题编号重置。
例如,
是否有可能在postgresql中生成这样的序列?我在考虑一些创造功能,但我对它们的用法并不是很熟悉。
任何提示都将不胜感激。
戈登的解决方案是最干净的,但是我忘了提到我支持一些不允许我执行任何复杂更新的中间件。 然而我最终得到了触发器:
CREATE FUNCTION set_message_nb()
RETURNS trigger AS '
DECLARE
max_for_topic int;
BEGIN
max_for_topic := (SELECT max(message_nb_in_topic) FROM MESSAGE WHERE topic_id=NEW.topic_id);
IF max_for_topic IS NULL THEN
NEW.message_nb_in_topic := 1;
ELSE
NEW.message_nb_in_topic := 1 + max_for_topic;
END IF;
RETURN NEW;
END' LANGUAGE 'plpgsql';
CREATE TRIGGER add_messagenb_at_insert
BEFORE INSERT ON MESSAGE
FOR EACH ROW
EXECUTE PROCEDURE set_message_nb();
答案 0 :(得分:1)
你不需要自己的功能; row_number()
为您做到了这一点:
select m.*,
row_number() over (partition by topic order by message_global_id) as seqnum
from messages m;
我想念你想要一个update
:
update messages m
set message_nb_in_topic = mm.seqnum
from (select m.*,
row_number() over (partition by topic order by message_global_id) as seqnum
from messages m
) mm
where m.message_global_id = mm.message_global_id;