MySQL 關閉子表的外鍵約束檢察

來源:互聯網
上載者:User

標籤:

準備:

  定義一個教師表、一個學生表;在學生表中引用教師表ID

create table teachers(teacherID int not null auto_increment primary key,teacherName varchar(8));

create table students(studentID int not null auto_increment primary key,teacherID int not null,studentName varchar(8),

  constraint fk_students_teacherID foreign key (teacherId) references teachers(teacherId) on delete no action on update cascade);

第一步:

  插入一個老師

  insert into teachers(teacherName) values(‘NameA‘);

  

  插入一個學生:

  insert into students(studentName,teacherID) values(‘NameB‘,100);--可以知道沒有這個教師號、所以插入會出錯。

  

 

  不過有沒有辦法可以插入一條不合理的資料呢?辦法還是有的

第二步:

  set foreign_key_checks = 0; 這樣就可以了。

  insert into students(studentName,teacherID) values(‘NameB‘,100);

  

第三步:

  設定回預設值、保持外鍵約束檢察。

  set foreign_key_checks =1;

 

總結:

  這篇隨筆寫的特別的亂、我想說的重點就是 set foreign_key_checks =0;時外鍵約束是沒有用的。這時可以對子表進行違反外鍵約束的插入。

  不到萬不得以不要用這個。

  

  

  

 

MySQL 關閉子表的外鍵約束檢察

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.