2014-03-13 114 views
1

我有两个表,一个是table #1包含用户信息,电子邮件,密码等。返回值交叉连接

其他表#2中包含项目信息

当我做一个INSERT INTO table #2 ,然后使用返回语句来收集插入的内容(返回自动值以及其他信息),我还需要从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) 
换句话说

,插入后,我需要返回插入值,以及有关谁插入数据的用户的信息。

这可能吗?

我想出的唯一办法是在返回子句中使用一大堆子查询语句。一定有更好的方法。

回答

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 
    ); 
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,这是一个保留字工作。