2015-08-15 77 views
1

说我有如下的表:Postgres的 - 插入和复合外键

a: integer 
b: integer 
c: integer 
d: integer 
code: text 

(a, b) is a foreign key to another table 1 
(c, d) is a foreign key to another table 2 

插入很简单:

INSERT INTO table(a, b, c, d, code) VALUES(x1, y1, x2, y2, 'my code') 

现在,我想插入而获取的值我的复合外键a,bc,d在子查询中。类似这样的:

INSERT INTO table(a, b, c, d, code) VALUES 
((SELECT a, b FROM other-table-1 WHERE ...), 
(SELECT c, d FROM other-table-2 WHERE ...), 'my code') 

上面的查询不起作用,但它说明了我试图实现的目标。

另一种尝试,但还没有工作(子查询必须返回一个列):

INSERT INTO table(a, b, code) 
SELECT (SELECT a, b FROM other-table-1 WHERE ...), 
     (SELECT c, d FROM other-table-2 WHERE ...), 'my code') 

这在某种程度上可能吗?

回答

2

你必须使用下面的语法来插入记录,如果“我的代码”始终是这样的静态

INSERT INTO table(a, b, code) 
SELECT a, b, 'my code' FROM other-table WHERE ... 

如果你有多个表,那么你可以使用语法使用CTE

INSERT INTO table(a, b, c, d, code) 
WITH t1 AS (
    SELECT a, b FROM other-table-1 WHERE ... 
), t2 AS (
    SELECT c, d FROM other-table-2 WHERE ... 
) 
select t1.a, t1.b, t2.c, t2.d, 'my code' from t1,t2 
+0

CTE是新的对我来说,我会尝试一下!谢谢。 –

+0

如果你有样本日期,那么它将会是更全面的解决方案将在那里 – HaveNoDisplayName

+0

我会用有意义的数据来尝试它。如果我偶然发现问题,我会提出一个新问题。您指向CTE的指示在这里帮了我很多,谢谢! –

1

您的查询应该structuerd是这样的:

INSERT INTO table(a, b, c, d, code) 
SELECT x.a, x.b, y.c, y.d, 'my code' FROM other-table-1 AS x 
CROSS JOIN other-table-2 AS y 
WHERE ...