2016-06-22 16 views
0

世界!mysql多対多多くのカスケードの孤児を削除する

多対多の関係でレコードをカスケードすると、孤児が発生します。

DROP TABLE IF EXISTS skTable; 
DROP TABLE IF EXISTS studentTable; 
DROP TABLE IF EXISTS kTable; 
DROP TABLE IF EXISTS classTable; 

create table if not exists classTable (id int primary key) ENGINE=INNODB; 
insert into classTable values(1); 
insert into classTable values(2); 

create table if not exists studentTable (id int primary key, classID int, CONSTRAINT FOREIGN KEY (classID) REFERENCES classTable(id) ON DELETE CASCADE) ENGINE=INNODB; 
insert into studentTable values(1, 1); 
insert into studentTable values(2, 2); 

create table if not exists kTable (id int primary key) ENGINE=INNODB; 
insert into kTable values(1); 
insert into kTable values(2); 
insert into kTable values(3); 

create table if not exists skTable (id int primary key, studentID int, CONSTRAINT FOREIGN KEY(studentID) REFERENCES studentTable(id) on delete cascade, kID int, CONSTRAINT FOREIGN KEY(kID) REFERENCES kTable(id) on delete cascade) ENGINE=INNODB; 
insert into skTable values(1,1,1); 
insert into skTable values(2,2,2); 
insert into skTable values(3,2,3); 
insert into skTable values(4,1,2); 

DELETE FROM classTable WHERE id=2; 

私の期待はこれらのレコードを取得することです::これは(MySQL用の)私のSQLコードです

classTable、1つの記録:

id=1 

studentTable、1つの記録:

id=1, classID=1 

kTable、2 records:

id=1 
    id=2 

skTable、2つのレコード:

id=1, studentID=1, kID=1 
    id=4, studentID=1, kID=2 

問題は終わりにkTableが孤児である余分な記録

id=3 

を持っていることです。

おかげさまで L

答えて

0

skTablestudentTablekTableの子です。 studentTableclassTableの子です。 foriegnキーON DELETE CASCADEの場合、親で削除すると、子テーブルのデータは削除されます。しかし、その逆は不可能です。そのため、classTableのデータを削除すると、studentTableのデータが削除され、studentTableのデータが削除されたため、skTableのデータは削除されますが、kTableのデータは削除されません。

+0

ありがとうPhaneendra、今私は問題をよく理解しています。それをより良く設計するオプションはありますか、または私ができるのはトリガーやコードで孤児を管理することだけです。 –

+0

コードから管理する方が良い方法はありません。 –

関連する問題