標籤:exist img style 技術分享 ble database pre com character
外鍵的建立
方法1:建立表的時候設定(外鍵名隨機產生)
1.前提條件,必須要有一個主表,這裡設為persons
2.主表中必須設定主鍵欄位primary key,這裡設為id_p
//建立資料庫database(test)create database if not exists test character set utf8;//建立主表(persons)create table if not exists persons( id_p int not null, lastName varchar(15) not null, firstName varchar(15) not null, address varchar(20) not null, city varchar(15) not null, primary key(id_p) //設定主鍵,這裡必須要設定);
//插入資料
//建立從表(orders)create table if not exists orders( id_o int not null, orderNo int not null, id_p int not null, primary key(id_o), foreign key(id_p) references persons(id_p) //設定外鍵,兩個欄位名id_p不需要一致,但是資料類型必須一致);
//插入資料
方法2:建立外鍵名的方式設定
alter table orders add constraint fk_id foreign key(id_p) references persons(id_p);
外鍵的刪除
1.先查出它的外鍵
show create table orders;
2.刪除外鍵
alter table orders drop foreign key order_ibfk_1;
mysql中外鍵的建立與刪除