Sql Postgres-插入和组合外键
假设我有一个包含以下列的表:Sql Postgres-插入和组合外键,sql,postgresql,foreign-keys,primary-key,composite-key,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: 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, 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 ...
当然,上面的查询不起作用,但它说明了我正在努力实现的目标
再次尝试,但也不起作用(子查询必须返回一列):
这可能吗?如果“我的代码”始终是静态的,则必须使用以下语法插入记录
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
您的查询的结构应如下所示:
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, 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 ...
CTE对我来说是新的,我会尝试一下!谢谢。如果你有样品日期,那么它会更完整。我会用有意义的数据来尝试。如果我遇到问题,我会提出一个新问题。你指向CTE的指针在这里帮助了我很多,谢谢!