在postgres中插入自动增量id

时间:2014-06-24 12:53:47

标签: sql postgresql insert

我想为表sd_roles创建插入脚本。某些行需要具有其他行ID的值。

使用此脚本创建sd_roles表:

-- Table: sd_roles

-- DROP TABLE sd_roles;

CREATE TABLE sd_roles
(
  id integer NOT NULL DEFAULT nextval('roles_serials'::regclass),
  masterid integer,
  rname character varying(150) NOT NULL,
  CONSTRAINT sd_roles_pkey PRIMARY KEY (id),
  CONSTRAINT rname_unique UNIQUE (rname)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE sd_roles
  OWNER TO postgres;
GRANT ALL ON TABLE sd_roles TO postgres;
GRANT ALL ON TABLE sd_roles TO eomeroff;

-- Trigger: lowecase_roles_on_insert_trigger on sd_roles

-- DROP TRIGGER lowecase_roles_on_insert_trigger ON sd_roles;

CREATE TRIGGER lowecase_roles_on_insert_trigger
  BEFORE INSERT OR UPDATE
  ON sd_roles
  FOR EACH ROW
  EXECUTE PROCEDURE lowecase_roles_on_insert();

我有这段代码:

    DELETE FROM sd_roles;


    WITH appconfiguration AS (
        INSERT INTO sd_roles
            (masterid, rname)
        VALUES
            (null, 'Appconfiguration')
        RETURNING id
    )
    INSERT INTO sd_roles (masterid, rname)
    VALUES ((SELECT id FROM appconfiguration), 'GroupsandRolesConfig');

现在我需要添加代码以插入另一行,其中包含" masterid"字段等于具有" rname"的行的id值等于" GroupsandRolesConfig"。以与行相同的方式" rname"字段是" GroupsandRolesConfig"有" masterid"行的id是" rname"字段是"应用程序配置"。

我的问题是跟随cluase的inser子句不能记住插入值的id,因此我可以重用它。

怎么做?

2 个答案:

答案 0 :(得分:1)

您可以拥有多个CTE,您可以根据需要将它们链接起来。

     WITH appconfiguration AS (
        INSERT INTO sd_roles
            (masterid, rname)
        VALUES
            (null, 'Appconfiguration')
        RETURNING id
    ), groups AS (
      INSERT INTO sd_roles (masterid, rname)
        VALUES ((SELECT id FROM appconfiguration), 'GroupsandRolesConfig')
      RETURNING id
    )
    INSERT INTO sd_roles (masterid, rname)
        VALUES ((SELECT id FROM groups), 'foobar');

http://sqlfiddle.com/#!15/3cebb/3

答案 1 :(得分:0)

此代码有效:

DELETE FROM sd_roles;

    INSERT INTO sd_roles (masterid, rname)
    VALUES (null, 'Superadmin');

    WITH appconfiguration AS (
        INSERT INTO sd_roles
            (masterid, rname)
        VALUES
            (null, 'Appconfiguration')
        RETURNING id
    )
    INSERT INTO sd_roles (masterid, rname)
    VALUES ((SELECT id FROM appconfiguration), 'Database'),
            ((SELECT id FROM appconfiguration), 'GroupsandRolesConfig');

    WITH groupsandRolesConfig AS (
         SELECT * FROM sd_roles where rname = LOWER('GroupsandRolesConfig')
    )
    INSERT INTO sd_roles (masterid, rname)
    VALUES ((SELECT id FROM groupsandRolesConfig), 'AddDeleteGroups'),
            ((SELECT id FROM groupsandRolesConfig), 'AssignRolesToGroups');