2011-02-11 63 views
3

我有一個SELECT這樣的查詢:我可以使用來自兩個連接表的數據編寫插入查詢嗎?

SELECT id_default_value, id_type FROM ntg_attribute, ntg_module_attribute 
WHERE ntg_attribute.id_module_attribute = ntg_module_attribute.id; 

這將返回2列,id_default_valueid_type。然後,我想使用此數據作爲INSERT查詢到另一個表中的基礎,ntg_default_value,使用id_default_value作爲關鍵字,並使用id_type作爲插入值。

以下是幾乎沒有,但並不完全:

INSERT INTO ntg_default_value (id, id_type) 
SELECT id_default_value, id_type FROM ntg_attribute, ntg_module_attribute 
WHERE ntg_attribute.id_module_attribute = ntg_module_attribute.id; 

這給了我:

ERROR: duplicate key value violates unique constraint "pk_ntg_default_value" 

是什麼,我想真正做可能嗎?如果是這樣,我該如何構建查詢?

(PostgreSQL的8.4.6)

+0

其可能性。該錯誤表示主鍵已經存在,並且新行具有重複鍵。你需要構造一個適當的條件,只選擇不會重複你的PK的「新」行。一個常見的習慣用法是insert into foo(...)select ... from bar ... where exists(where from foo where where bar.id = foo.pk)` - 將排除PK已經存在的行。 – 2011-02-11 21:35:11

+0

你爲什麼要將數據複製到另一個表中? – blthiewes 2011-02-12 16:53:54

回答

1

約束「pk_ntg_default_value」的名稱可能意味着你違反了表ntg_default_value的主鍵約束。

根據您的要求,您可以帶走主鍵約束。或者,您可以將它擴展爲包含id爲&的id_type(如果它尚未包含),並在必要時向查詢添加GROUP BY以防止重複id_devault_value & id_type對。您的查詢變爲:

INSERT INTO ntg_default_value (id, id_type) 
SELECT id_default_value, id_type 
FROM ntg_attribute, ntg_module_attribute 
WHERE ntg_attribute.id_module_attribute = 
     ntg_module_attribute.id 
GROUP BY id_default_value, id_type 
相關問題