程式媛計劃——mysql外鍵

來源:互聯網
上載者:User

標籤:主表   python   query   mysql外鍵   mysql   for   size   alter   tab   

定義

外鍵:如果一個表的某個欄位指向另一個表的主鍵,就稱之為外鍵。被指向的表,稱之為主表,也叫父表,那麼另一個表就是從表,也叫子表

 

#先建立兩個表

mysql> create table author_table(    -> author_id int(4) not null primary key auto_increment,    -> author_name char(20) not null);Query OK, 0 rows affected (0.02 sec)
mysql> create table article_table(    -> article_id int(4) not null primary key auto_increment,    -> article_title char(20) not null,    -> author_id int(4) not null,    -> foreign key(author_id) references author_table(author_id));  #這一步使得article_table中的author_id欄位成為外鍵Query OK, 0 rows affected (0.02 sec)

#添加資料

mysql> insert into author_table values    -> (1,‘zhao‘),    -> (2,‘qian‘),    -> (3,‘sun‘),    -> (4,‘li‘);Query OK, 4 rows affected (0.01 sec)Records: 4  Duplicates: 0  Warnings: 0
mysql> insert into article_table values    -> (1001,‘c++‘,1),    -> (1002,‘java‘,1),    -> (1003,‘python‘,2),    -> (1004,‘mysql‘,3),    -> (1005,‘jacascript‘,4);Query OK, 5 rows affected (0.00 sec)Records: 5  Duplicates: 0  Warnings: 0

 

#子表和附表之間的約束

0 article_table中不能添加author_id為5的記錄;

1 author_table中不能刪除author_id為4的記錄,因為子表中還有作者4的文章

 

#刪除外鍵約束

mysql> alter table article_table drop foreign key article_table_ibfk_1;Query OK, 0 rows affected (0.02 sec)Records: 0  Duplicates: 0  Warnings: 0

 

#級聯操作

#添加外鍵

mysql> alter table article_table    -> add foreign key fk_id(author_id)  #這裡fk_id可以自己指定    -> references author_table(author_id)    -> on delete cascade  #cascade表示關聯操作。子表會依賴父表中的資料關聯刪除或更新    -> on update cascade;    Query OK, 5 rows affected (0.02 sec)Records: 5  Duplicates: 0  Warnings: 0

 

#set null關鍵字

set null,表示子表資料不指向父表任何記錄。當不加set null和cascade時,預設為restrict(拒絕主表的相關操作),所以開始主表無法刪除資料

 

程式媛計劃——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.