sql - Cannot insert into field with primary key constraint in PostgreSQL -


i have "raw" table looks (among other many fields):

 team_id |        team_name         ---------+-------------------------        1 | team1        1 | team1        2 | team2        2 | team2 

i want extract team names , id codes , create table them, created:

    create table teams (         team_id integer not null,         team_name varchar(50) not null,         constraint team_pkey primary key (team_id) ); 

and planning copy data old table created 1 this:

insert teams(team_id,team_name)                                         select team_id,team_name rawtable  group team_id, team_name;  

at first wasn't adding group by part, , getting message:

error:  duplicate key value violates unique constraint "team_pkey" 

i added group by doesn't try insert more 1 row same team, problem still persist , keep getting same message.

i don't understand causing it. looks inserting single non duplicate rows table. what's best way fix this?

if 2 different teams same id in raw_table e.g. (1, 'foo') , (1, 'bar') group by still return both, because 2 are different.

if want pick one of rows duplicate values of team_id should use this:

insert teams (team_id,team_name)   select distinct on (team_id) team_id, team_name rawtable order team_id; 

the postgres specific distinct on operator make sure distinct values team_id returned.


Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -