Postgresql:生成默认音量值为整数等级

时间:2016-03-01 02:08:33

标签: sql postgresql

假设我在下面的(虚构)表中将消息存储在讨论板中,按主题组织,本身由整数标识:

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设置为序列的等效值,但是会为每个主题编号重置。

例如,

  • 我发布主题0 - >消息有message_nb_in_topic = 0
  • 我发布主题0 - >消息有message_nb_in_topic = 1
  • 我发布主题1 - >消息有message_nb_in_topic = 0
  • 我发布主题0 - >消息有message_nb_in_topic = 2
  • 我发布主题1 - >消息有message_nb_in_topic = 1
  • 我发布主题2 - >消息有message_nb_in_topic = 0

是否有可能在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();

1 个答案:

答案 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;