我有三个表:clients,items和client_has_item。
CREATE TABLE clients (id_c serial primary key, name text);
CREATE TABLE items (id_i serial primary key, name text);
CREATE TABLE client_has_item
(id_c int references clients (id_c),
id_i int references items (id_i));
INSERT INTO clients (name) values ('client a'), ('client b');
INSERT INTO items (name) values ('item a'), ('item a');
请注意,客户可以拥有多个项目,一个项目可以由多个客户拥有,而且名称不是唯一的。
如果我想为一个客户端插入一些项目(1,'客户端a'),那很简单:
WITH inserted_items as (
INSERT INTO items (name) values ('item a'), ('item b')
RETURNING id_i
)
INSERT INTO client_has_item (id_c, id_i) select 1, id_i from inserted_items
我的问题是如何为几个客户执行此操作。理想情况下我会这样做:
WITH inserted_items as (
INSERT INTO items (name) SELECT new_items.item_name from (values (1, 'item a'), (2, 'item b')) new_items (id_client, item_name)
RETURNING items.id_i, new_items.id_client
)
INSERT INTO client_has_item (id_c, id_i) select id_client, id_i from inserted_items
但是我收到以下错误:
RETURNING items.id_i, new_items.id_client
********** Error **********
ERROR: missing FROM-clause entry for table "new_items"
什么是最好的选择?当然我可以做一个循环,但我想避免这种情况。