2011-02-11 21 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 
相关问题