2

Part of my SQL definition (for ):

CREATE TABLE activities (
  id  BIGINT GENERATED BY DEFAULT AS IDENTITY,
  group_id  BIGINT NOT NULL
  CONSTRAINT pk_activities PRIMARY KEY (id)
);

The scenario during and insert is:

  • id is auto generated / auto-incremented,
  • group_id when specified (non-null) is set to the given value,
  • group_id when not specified is set to the value of id just generated

I target and (for tests).

Can this be done?

4

2 回答 2

1

您不能将默认值设置为另一列的默认值。

但是,您可以创建一个触发器来完成此任务。

这是 PostgreSQL 的一个示例。如果它在或之前,它会自动替换column为:anothercolumnNULLINSERTUPDATE

CREATE OR REPLACE FUNCTION mytable_fn()
RETURNS trigger AS
$body$
BEGIN
    IF NEW.column ISNULL THEN
        NEW.column := NEW.anothercolumn;
    END IF;
    RETURN NEW;
END;
$body$
LANGUAGE 'plpgsql';

CREATE TRIGGER mytable_trigger
BEFORE INSERT OR UPDATE ON mytable
FOR EACH ROW
EXECUTE PROCEDURE mytable_fn();
于 2013-04-03T09:20:37.640 回答
1

这可以使用触发器来完成,或者如果您不想使用触发器,则在选择这样的行时处理 NULL:

SELECT id, isnull(group_id, id) group_id FROM activities;
于 2013-04-03T09:26:39.650 回答