【问题标题】:Postgres - insert and composite foreign keysPostgres - 插入和复合外键
【发布时间】:2015-11-08 10:52:03
【问题描述】:

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

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

这有可能吗?

【问题讨论】:

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


    【解决方案1】:

    如果“我的代码”始终是静态的,则必须使用以下语法插入记录

    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
    

    【讨论】:

    • CTE 对我来说是新的,我会试试看!谢谢。
    • 如果你有样品日期,那么会有更全面的解决方案
    • 我会用有意义的数据来试试。如果我偶然发现问题,我会提出一个新问题。您对 CTE 的指点在这里帮助了我很多,谢谢!
    【解决方案2】:

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

    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 ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      相关资源
      最近更新 更多