2017-08-06 105 views
-1

我有表格:作者獎勵(一對多關係)。我想制定下一條規則:爲什麼'從表中刪除'忽略外鍵約束?

  • 獎勵已鏈接到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) 
; 
+0

「限制刪除獎勵,如果它有author_id外鍵」。由於author_id被定義爲NOT NULL,這意味着您不能刪除任何獎勵,除非您刪除整個作者。是對的嗎? – Progman

+0

我不明白這個問題。你說:「我怎樣才能避免從獎勵中刪除?」但是在上面你指定你想要級聯刪除。 –

+0

@GordonLinoff是的,我的意思是我想限制'從獎勵哪裏刪除......「。並允許從作者級聯刪除 – Nikolas

回答

0

與觸發器很容易,但你需要也許是基於另一個表的覆蓋選項。

drop trigger if exists delete_rewards; 
delimiter $$ 

CREATE DEFINER=`root`@`localhost` TRIGGER `delete_rewards` BEFORE delete ON `rewards` 
FOR EACH ROW 
begin 
    declare msg varchar(100); 
    declare found int; 
    set found = 0; 
    select count(*) into found from authors a where a.author_id = old.author_id; 

    if found > 0 then 
     set msg = 'Delete Not allowed'; 
     signal sqlstate '45000' set message_text = msg; 
    end if; 


END $$ 

delimiter ; 
0

在制定約束時,您不能刪除作者而不刪除所有獎勵。但是,您可以根據需要刪除獎勵。這是一個典型的一對多關係,其中一個是作者和很多是獎勵。這是有道理的,因爲只要許多指的是你不想刪除一個。 級聯將工作。

如果您想要防止處理獎勵記錄,只要他們被分配,我建議觸發器和可能的歷史表。

如果你想要一個獎勵和許多作者,你必須扭轉關係。所以作者必須參考他們的獎勵。如果它很多很多,你將需要一個額外的表來處理這個問題。但看到你最後的情況,我懷疑事實並非如此。