2014-01-16 53 views
0

         如果有可能在表中插入同一行我想忽略這一個。這裏有外鍵game_id和2個字段step_num和cell的表,它們可能不同,應該有所不同。 Cell應該是0-8,並且對於game_id總是不同的。 Step_num相同,但是1-9。但是我無法設置唯一性,因爲它們可能是相同的,但是在不同的game_id中。

這裏是腳本的一部分:約束在同一行

create table games(
    id int not null auto_increment primary key, 
    name varchar(255) not null unique , 
    status varchar(255) not null, 
    createDate DATETIME 
); 

create table steps(
    game_id int not null , 
    step_num int not null, 
    cell int not null, 
    constraint cell_unique on games(id), 
    constraint chk_number check(step_number > 0 and step_number < 10), 
    constraint fk_game foreign key (game_id) references games(id) on delete cascade, 
    constraint chk_cell check(cell >= 0 and cell <= 8) 
); 

INSERT IGNORE沒有工作的ADN上插入重複鍵我覺得不是我所需要的。如果我嘗試多次插入(2,2,2),它應該忽略。我在後端防止這種行爲,但希望這個數據庫是正確的,並自動阻止類似的行爲。


有什麼方法可以正確地做到這一點?

回答

1

你有2種選擇:

  1. 定義使用(game_id, step_num, cell)複合主鍵。這會限制重複的行數據,如2, 2, 2

  2. 定義一個before insert trigger檢查重複項,並且 限制使用相同值更新同一行,不影響任何行。

而據我所知,check約束在MySQL沒有影響。

+0

複合主鍵運作良好!非常感謝! – lummycoder