sql - Postgres - 插入和复合外键

标签 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')

这有可能吗?

最佳答案

如果'我的代码'总是静态的,你必须使用下面的语法来插入记录

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/

相关文章:

database - 外键 SQL Server

sql - 在 SQL Server 中使用 MD5 哈希作为主键与使用 int 标识作为主键的优缺点

sql - MySQL:将 NULL 类型转换为 0

java - 调用 Postgres 存储函数 SQL 错误

PostGreSQL 负载随时间增加,为什么?

mysql - 自动删除连接数据以及删除记录?

sql - 静态 vs 动态 sql

sql - 无法让 DISTINCT + GROUP 与具有两个值的 Postgres 一起使用

java - 如何在 HQL 中传递特殊字符?

MySql 检查外键约束是否存在