Postgres - 插入和复合外键
Postgres - insert and composite foreign keys
假设我有一个包含以下列的 table:
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,b
和 c,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')
上面的查询当然不起作用,但它说明了我正在努力实现的目标。
再次尝试,但还是不行(子查询必须 return 一列):
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')
这有可能吗?
你必须使用下面的语法来插入记录,如果'my code'总是静态的
INSERT INTO table(a, b, code)
SELECT a, b, 'my code' FROM other-table WHERE ...
如果您有多个 table,那么您可以使用 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
您的查询应该像这样构造:
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 ...
假设我有一个包含以下列的 table:
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,b
和 c,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')
上面的查询当然不起作用,但它说明了我正在努力实现的目标。
再次尝试,但还是不行(子查询必须 return 一列):
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')
这有可能吗?
你必须使用下面的语法来插入记录,如果'my code'总是静态的
INSERT INTO table(a, b, code)
SELECT a, b, 'my code' FROM other-table WHERE ...
如果您有多个 table,那么您可以使用 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
您的查询应该像这样构造:
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 ...