开发者

Can I write an insert query using data from two joined tables?

开发者 https://www.devze.com 2023-02-10 05:03 出处:网络
I have a SE开发者_运维技巧LECT query like this: SELECT id_default_value, id_type FROM ntg_attribute, ntg_module_attribute

I have a SE开发者_运维技巧LECT query like this:

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

This returns 2 columns, id_default_value and id_type. I'd like to then use this data as the basis of an INSERT query into another table, ntg_default_value, using id_default_value as the key, and id_type as the inserted value.

The following is nearly there, but not quite:

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;

This gives me:

ERROR:  duplicate key value violates unique constraint "pk_ntg_default_value"

Is what I'm trying to do actually possible? If so, how do I construct the query?

(PostgreSQL 8.4.6)


The name of the constraint 'pk_ntg_default_value' probably means you are violating the primary key constraint of the table ntg_default_value.

Depending on your requirements you can either take away the primary key constraint. Or you can expand it to include both id & id_type if it doesn't already and add a GROUP BY to your query, if necessary, to prevent duplicate id_devault_value & id_type pairs. Your query becomes then :

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
0

精彩评论

暂无评论...
验证码 换一张
取 消