无法在 PostgreSQL 中插入具有主键约束的字段

Cannot insert into field with primary key constraint in PostgreSQL

我有一个 "raw" table 看起来像这样(在其他许多字段中):

 team_id |        team_name        
---------+-------------------------
       1 | Team1
       1 | Team1
       2 | Team2
       2 | Team2

我想提取团队名称和他们的 ID 代码并为他们创建另一个 table,所以我创建了:

    CREATE TABLE teams (
        team_id integer NOT NULL,
        team_name varchar(50) NOT NULL,
        CONSTRAINT team_pkey PRIMARY KEY (team_id)
);

我打算将数据从旧 table 复制到最近创建的数据,如下所示:

INSERT INTO teams(team_id,team_name)                                        
SELECT team_id,team_name FROM rawtable 
GROUP BY team_id, team_name; 

起初我没有添加 GROUP BY 部分,我收到一条消息:

ERROR:  duplicate key value violates unique constraint "team_pkey"

我添加了 GROUP BY,因此它不会尝试为同一个团队插入多行,但问题仍然存在,我不断收到相同的消息。

我不明白是什么原因造成的。看起来我正在将单个非重复行插入 table。解决此问题的最佳方法是什么?

尝试在查询中使用 distinct :

insert into teams (team_id,team_name) select distinct on (team_id) team_id, team_name from order by team_id;

您的 Team1 或 Team2 中的一个可能有一些额外的空格或不可打印的字符。这会导致您的分组 return 多行 Team_ID 1 或 2 导致问题。

我最好的猜测是,您至少在 table 的某处有一个 team_name 相同的 team_id。尝试将 `Having count(*)=1 添加到您的 select 语句

如果两个具有相同 ID 的不同团队在 raw_table 中,例如(1, 'foo')(1, 'bar') group by 仍然会 return 两者,因为这两个 不同的。

如果您只想为 team_id 的重复值选择 一个 行,那么您应该使用这样的东西:

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

Postgres 特定的 distinct on 运算符将确保只有 team_id 的不同值被 returned。

由于 team_id 在目标 table 中是唯一的,两个具有相同 ID 的独立团队名称将创建重复项,每个名称一行。

一个简单的解决方法是按 team_id 分组,这样每个 id 只能得到一行,然后选择团队的名称之一(这里我们有点武断地使用 MAX 来获取字母顺序中的最后一个顺序)

INSERT INTO teams(team_id,team_name)                                        
 SELECT team_id, MAX(team_name) FROM rawtable 
 GROUP BY team_id