2015-08-15 46 views
1

說我有如下的表:Postgres的 - 插入和複合外鍵

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

這在某種程度上可能嗎?

回答

2

你必須使用下面的語法來插入記錄,如果「我的代碼」始終是這樣的靜態

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 
+0

CTE是新的對我來說,我會嘗試一下!謝謝。 –

+0

如果你有樣本日期,那麼它將會是更全面的解決方案將在那裏 – HaveNoDisplayName

+0

我會用有意義的數據來嘗試它。如果我偶然發現問題,我會提出一個新問題。您指向CTE的指示在這裏幫了我很多,謝謝! –

1

您的查詢應該structuerd是這樣的:

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