1. 程式人生 > >【MySQL-效能優化】--MySQL外來鍵約束簡述

【MySQL-效能優化】--MySQL外來鍵約束簡述

建立表users

CREATE TABLE users(

             id int  AUTO_INCREMENT PRIMARY KEY,

 authority char(20) NOT NULL,

             operationid char(10) NOT NULL,

             status char(10) NOT NULL,

             username char(20) NOT NULL,

             password char(20) NOT NULL,

             realname char(20) NOT NULL,

             tel char(20) NOT NULL,   

department char(30) NOT NULL,

             checkintime date NOT NULL,

             resigntime date NULL);

注意:為users表的authority和department兩個欄位建立外來鍵約束,當然啦,前提是先建立好這連個表。

OK,先 建立authority表吧!

--建立使用者許可權表

CREATE TABLE authority(

             name char(20) NOT NULL PRIMARY KEY);

接著,我們再來建立department表:

--建立使用者所屬部門表

CREATE TABLE department(

             name char(30) NOT NULL PRIMARY KEY);

好了,現在開始建立外來鍵約束吧!

--給users表的部門(department)和許可權(authority)新增外來鍵

Alter table users add foreign key(department) references department(name) on delete restrict on update cascade;

Alter table users add foreign key(authority) references authority(name) on delete restrict on update cascade;

好了,問題來了,建立約束之後,authority和department的內容是限制更改的,如果想改變的話,怎麼辦?先修改users表中與authority和department對應的資訊,之後就可以修改了。什麼意思呢?

上圖吧!

insert into authority(name)values('總檢員');

insert into authority(name)values('打包員');

insert into authority(name)values('操作員');

insert into authority(name)values('管理員');


insert into department(name)values('管理部');

insert into department(name)values('工程部');


insert into users(authority,operationid,status,username,password,realname,tel,department) values('管理員','12345','離職','admin','123456','章撒','787878','管理部');

看到了嗎?建立好authority與department後,才能在users中新增資訊,而且特別注意的是,在users表中的authority和department這兩個欄位的資訊,必須與外來鍵表authority和department中的資訊保持一致才不會出錯,否則的話,插入會失敗!!!

如果想要修改外來鍵authority或者department中的內容,前提是要在users表中將authority和department這兩個欄位的資訊修改,也就是與外來鍵脫離才行,否則也是修改失敗!!

OK,就這麼多了,抓緊試一下吧!

補充個小知識:

  • 清空資料表:truncate table **;

  • 刪除資料表:delete from table_name WHERE name = '***';

mysql中Unicode編碼,1個字元=2個位元組,漢字=4個位元組,