PostgreSQL插入数组的多对多关系

时间:2016-09-16 19:32:44

标签: arrays postgresql many-to-many sql-insert

让许多用户属于多个群组。

编写一个功能,创建一个包含name和用户列表的组。

1 个答案:

答案 0 :(得分:-1)

CREATE FUNCTION groups_create(varchar(50), bigint[]) RETURNS SETOF bigint AS
$$
    WITH g AS (
        INSERT INTO groups (name)
        VALUES ($1)
        RETURNING id
    ), gm AS (
        INSERT INTO group_members
        SELECT id, unnest($2) FROM g
    )
    SELECT id FROM g
$$
LANGUAGE SQL;

http://sqlfiddle.com/#!15/9e408/9