データベース中外キーSQL文の作成


データベース中外キーSQL文の作成
1.外部キー拘束作用
外部キー制約:外部キーフィールドの値を更新して挿入すると、参照テーブルのフィールドのデータと検証されます.データが法則に合わない場合、更新と挿入が失敗し、データの有効性が保証されます.
2.既存のフィールドに外部キー制約を追加
--  cls_id        
alter table students add foreign key(cls_id) references classes(id);  【      ,       】

3.データテーブルの作成時に外部キー制約を設定する
--      
create table school(
    id int not null primary key auto_increment, 
    name varchar(10)
);

--      
create table teacher(
    id int not null primary key auto_increment, 
    name varchar(10), 
    s_id int not null, 
    foreign key(s_id) references school(id)
);

4.外部キー制約の削除
--            ,          ,                
show create table teacher;

--                     
alter table teacher drop foreign key    ;

5.まとめ
  • 外部キー制約の追加:alter tableスレーブadd foreign key(外部キーフィールド)referencesプライマリテーブル(プライマリキーフィールド);
  • 外部キー制約の削除:alter tableテーブル名drop foreign key外部キー名;