假设我有一个包含以下列的表格:
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')
上面的查询当然不起作用,但它说明了我正在努力实现的目标。
再试一次,但还是不行(子查询必须返回一列):
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')
这有可能吗?
最佳答案
如果'我的代码'总是静态的,你必须使用下面的语法来插入记录
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
关于sql - Postgres - 插入和复合外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32022650/