将值一次插入到2个表中-Postgres

时间:2019-10-19 00:47:06

标签: postgresql sql-insert

我有两个表,我试图同时向两个表中添加数据,但是我无法使插入工作。

这些表是:

CREATE TABLE "user" (
    "id" SERIAL PRIMARY KEY,
    "username" VARCHAR (80) UNIQUE NOT NULL,
    "password" VARCHAR (1000) NOT NULL,
    "admin" boolean DEFAULT FALSE
);

CREATE TABLE "user_info" (
"id" SERIAL PRIMARY KEY,
"first_name" varchar(60) NOT NULL,
"last_name" varchar(60) NOT NULL,
"email" varchar(120),
"street" varchar(200),
"city" varchar(200),
"state" varchar(2),
"zipcode" varchar(20),
"phone" INT,
"user_login_id" INT REFERENCES "user"
);

我尝试的代码是:

WITH "user_insert" as (
INSERT INTO "user" ("username", "password") 
VALUES ('larry', 'root')
RETURNING "id" as "user_login_id"
),
"second_insert" as (
INSERT INTO "user_info"("first_name", "last_name", "email", "street", "city", "state", "zipcode", "phone", "user_login_id")
VALUES ('larry', 'marry', '222@gmail.com', '222 adam street', 'saint paul', 'MN', '55101', '5551113333', 
(select id from "user")
);

我期望的是将这些值添加到它们各自的表中。 有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

首先,您需要一条SQL语句来遵循CTE。

此外,我怀疑您是否需要所有双引号。最好定义没有它们的表和列。

我认为以下方法应该有效:

WITH u as (
     INSERT INTO user (username, password)
         VALUES ('larry', 'root')
         RETURNING id
     )
INSERT INTO user_info (first_name, last_name, email, street, city, state, zipcode, phone, user_login_id) 
    SELECT 'larry', 'marry', '222@gmail.com', '222 adam street', 'saint paul', 'MN', '55101', '5551113333', u.id
    FROM u;