Postgres - 插入和复合外键

时间:2015-08-15 07:47:34

标签: sql postgresql foreign-keys primary-key composite-key

假设我有一个包含以下列的表:

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 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

您的查询应该是这样的结构:

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 ...
相关问题