对同一行的约束

时间:2014-01-16 08:17:17

标签: mysql insert duplicates

如果表中可能插入了同一行,我想忽略这一行。这里有外键game_id和2个字段step_num和cell的表,它们可能不同,应该有所不同。对于game_id,Cell应该是0-8并且总是不同的。 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 INSERT ON DUPLICATE KEY我认为不是我需要的。如果我多次尝试插入(2,2,2),它应该忽略。我在后端防止此操作,但希望db正确并自动阻止类似操作

有哪些正确的方法?

1 个答案:

答案 0 :(得分:1)

您有两个选择:

  1. 使用( game_id, step_num, cell )定义复合主键。这会限制重复的行数据,例如2, 2, 2

  2. 定义检查重复项的before insert trigger  限制,使用相同的值更新同一行,不影响任何行。

  3. 根据我的知识check约束对MySQL无效。