我有两个表,一个是table #1
包含用户信息,电子邮件,密码等。
另一个表#2包含项目信息
当我插入table #2
,然后使用return语句来收集插入的内容(返回自动值以及其他信息)时,我还需要从table #1
返回信息
(借口语法)
示例:
insert into table #1(item,user) values('this item','the user')
returning *, select * from table 2 where table #1.user = table #2.user)
换句话说,插入后我需要返回插入的值,以及有关插入数据的用户的信息。
这可能吗?
我唯一想到的是在返回子句中使用一大堆子查询语句。必须有更好的方法。
答案 0 :(得分:4)
我建议使用data-modifying CTE(Postgres 9.1或更高版本):
WITH ins AS (
INSERT INTO tbl1(item, usr)
VALUES('this item', 'the user')
RETURNING usr
)
SELECT t2.*
FROM ins
JOIN tbl2 t2 USING (usr)
使用列名usr
而不是user
,这是一个保留字。
答案 1 :(得分:1)
使用子查询。
简单演示:http://sqlfiddle.com/#!15/bcc0d/3
insert into table2( userid, some_column )
values( 2, 'some data' )
returning
userid,
some_column,
( SELECT username FROM table1
WHERE table1.userid = table2.userid
);