我有表格:作者和獎勵(一對多關係)。我想制定下一條規則:爲什麼'從表中刪除'忽略外鍵約束?
- 獎勵已鏈接到author_id;
- 限制刪除獎勵,如果它有author_id外鍵;
- 當我刪除作者時,然後我想從這個author_id的獎勵表級聯刪除行。
我用
constraint foreign key (author_id)
references authors (author_id)
on delete cascade on update cascade
但無論如何,我可以從獎勵刪除行或所有行。我如何才能刪除獎勵只有當我刪除作者?
創建的表:
create table authors (
author_id bigint not null auto_increment,
birth_date datetime,
first_name varchar(255),
last_name varchar(255),
sex varchar(10),
primary key (author_id)
);
create table rewards (
reward_id bigint not null auto_increment,
title varchar(255),
year integer not null,
author_id bigint not null,
primary key (reward_id),
constraint foreign key (author_id) references authors (author_id)
on delete cascade on update cascade
);
然後插入值:
Insert into authors(
birth_date, first_name, last_name, sex) values
('1941-05-24', 'Bob', 'Dylan', 'male'),
('1870-10-22', 'Ivan', 'Bunin', 'male');
Insert into rewards(year, title, author_id) values
(2016, 'Nobel Prize for Literature', 1),
(1933, 'Nobel Prize for Literature', 2),
(1903, 'Pushkin Prize', 2)
;
「限制刪除獎勵,如果它有author_id外鍵」。由於author_id被定義爲NOT NULL,這意味着您不能刪除任何獎勵,除非您刪除整個作者。是對的嗎? – Progman
我不明白這個問題。你說:「我怎樣才能避免從獎勵中刪除?」但是在上面你指定你想要級聯刪除。 –
@GordonLinoff是的,我的意思是我想限制'從獎勵哪裏刪除......「。並允許從作者級聯刪除 – Nikolas