mysql中外鍵的建立與刪除

來源:互聯網
上載者:User

標籤: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中外鍵的建立與刪除

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.