在PostgreSql 9.2.4中,我有两个表:user (id, login, password, name)和dealer (id, user_id)。
user (id, login, password, name)
dealer (id, user_id)
我想在两个表中插入返回创建的经销商的ID。
目前,我正在使用两个查询来执行此操作:
WITH rows AS ( INSERT INTO "user" (login, password, name) VALUES ('dealer1', 'jygbjybk', 'Dealer 1') RETURNING id ) INSERT INTO dealer (user_id) SELECT id FROM rows; SELECT currval('dealer_id_seq');
但是我可以INSERT使用RETURNING语句通过单个查询实现此功能吗?
INSERT
RETURNING
你只需要一个添加RETURNING id到您的INSERT ... SELECT:
RETURNING id
INSERT ... SELECT
WITH rows AS (...) INSERT INTO dealer (user_id) SELECT id FROM rows RETURNING id;
演示:http : //sqlfiddle.com/#!12/75008/1