Mysql

消息 2627 違反主鍵約束

  • October 30, 2014

試圖在這里為電視節目中的團隊製作數據庫。但是當我嘗試將數據插入 tblShowteam 時,出現了以下錯誤。

Msg 2627, Level 14, State 1, Line 2
Violation of PRIMARY KEY constraint 'PK__tblShowt__F693078C03317E3D'. Cannot insert duplicate key in object 'dbo.tblShowteam'.

-- tabbellen aanmaken
create table tblShow(
setId       int,
Datum       date,
teams       int
primary key (setId));

create table tblShowteam(
SetId           int,
datum           date,
teams           int,
primary key (teams));


create table tblTeam(
TeamId      int,
Coach       varchar(35),
CoachId     int,
teams       int
primary key (CoachId));


-- participant table
create table tblDeelnemer(
DeelnemerId     int identity(1, 1),
DeelnemerV      varchar(35),
deelnemerT_V    varchar(10),
DeelnemerA      varchar(35),
CoachId         int,
datum_optreden  date
primary key (DeelnemerId));


--table for the public viewers
create table tblKijker(
Kijkerv         varchar(35),
KijkerT_V       varchar(10),
KijkerA         varchar(35),
Stoelnummer     int identity(1,3),
ShowId          int Not null,
Email           varchar(35)
primary key (Email));

我的插入看起來像這樣:

insert into tblShowteam values (1, '2014-06-28', 1)
insert into tblShowteam values (2, '2014-06-05', 1)
insert into tblShowteam values (3, '2014-06-12', 1)
insert into tblShowteam values (4, '2014-06-19', 1)
insert into tblShowteam values (5, '2014-06-26', 1)
all other inserts (in diffrent tables) work like normal.

我在這裡做錯了什麼?

tblShowteam 在teams列上有主鍵 (

創建表 tblShowteam(SetId int,基準日期,團隊 int,主鍵(團隊));

您正在多次插入具有相同主鍵 (1) 的行:

insert into tblShowteam values (1, '2014-06-28', 1);  
--the same as  "insert into tblShowteam (SetId,datum,teams) VALUES (...,1);
insert into tblShowteam values (2, '2014-06-05', 1) ; --it's gonna fail , record with 
-- teams = 1 already exists

我猜setId應該是主鍵,而不是teams.

在創建表中,您已將團隊設置為主鍵,並且您也知道主鍵不允許重複值。

mysql> create table tblShowteam(
       -> SetId           int,
       -> datum           date,
       -> teams           int,
       -> primary key (teams));
   Query OK, 0 rows affected (0.13 sec)

檢查您提到的值為 1 的團隊欄位的插入查詢,如果您為第二條記錄插入相同的值,它將表現如下。

  mysql> insert into tblShowteam values (1, '2014-06-28', 1);
   Query OK, 1 row affected (0.03 sec)

   mysql> insert into tblShowteam values (2, '2014-06-05', 1);
   ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'

請更改並保留SetId作為主鍵。

引用自:https://dba.stackexchange.com/questions/68779