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_value
和id_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)
其可能性。該錯誤表示主鍵已經存在,並且新行具有重複鍵。你需要構造一個適當的條件,只選擇不會重複你的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
你爲什麼要將數據複製到另一個表中? – blthiewes 2011-02-12 16:53:54