我想使用修改 CTE 来插入一些值。insert 语句从 select 语句中插入数据。我使用返回关键字来返回插入的值(包括自动递增的列)。但是,我也希望 CTE 返回其他列。我怎样才能做到这一点?
一个例子如下:
drop table if exists customers;
CREATE TABLE customers (
customer_id serial PRIMARY KEY,
name VARCHAR UNIQUE,
email VARCHAR NOT NULL,
active bool NOT NULL DEFAULT TRUE
);
INSERT INTO customers (NAME, email)
VALUES
('IBM', '[email protected]'),
(
'Microsoft',
'[email protected]'
),
(
'Intel',
'[email protected]'
);
drop table if exists customers2;
CREATE TABLE customers2 (
customer_id serial PRIMARY KEY,
name VARCHAR UNIQUE,
email VARCHAR NOT NULL
);
with x as (
INSERT INTO customers2 (NAME, email)
select name, email from customers
returning customer_id, name, email, active
)
select * from x
;
我希望最后一条语句返回列 customer_id、name、email、active。但我收到一个错误:
Error: ERROR: column "active" does not exist
Position: 123
SQLState: 42703
ErrorCode: 0
Error occurred in:
with x as (
INSERT INTO customers2 (NAME, email)
select name, email from customers
returning customer_id, name, email, active
)
select * from x
根据 Postgres Docs 大约6.4。从修改的行返回数据,你不能。
引用自文档:
除非此数据由触发器更新:
您可以使用
RETURNING *
db<>在这里摆弄
您可以通过使用嵌套 CTE 来获得它:
db<>在这里摆弄