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