資料庫MySQL 資料完整性

2021-10-04 11:30:13 字數 2530 閱讀 1322

1.5.1 資料完整性包括

1、實體完整性

1、主鍵約束

2、唯一約束

3、標識列

2、 域完整性

1、資料型別約束

2、非空約束

3、預設值約束

3、 引用完整性

外來鍵約束
4、 自定義完整性

1、儲存過程

2、觸發器

1.5.2 主表和從表

主表中沒有的記錄,從表不允許插入

從表中有的記錄,主表中不允許刪除

刪除主表前,先刪子表

1.5.3 外來鍵(foreign key)

外來鍵:從表中的公共字段

-- 建立表的時候新增外來鍵

drop table if exists stuinfo;

create table stuinfo(

id tinyint primary key,

name varchar(20)

)engine=innodb;

drop table if exists stuscore;

create table stuscore(

sid tinyint primary key,

score tinyint unsigned,

foreign key(sid) references stuinfo(id) -- 建立外來鍵

)engine=innodb;

-- 通過修改表的時候新增外來鍵

語法:alter table 從表 add foreign key(公共字段) references 主表(公共字段)

drop table if exists stuinfo;

create table stuinfo(

id tinyint primary key,

name varchar(20)

)engine=innodb;

drop table if exists stuscore;

create table stuscore(

sid tinyint primary key,

score tinyint unsigned

)engine=innodb;

alter table stuscore add foreign key (sid) references stuinfo(id)

刪除外來鍵

通過外來鍵的名字刪除外來鍵

-- 刪除外來鍵

mysql> alter table stuscore drop foreign key `stuscore_ibfk_1`;

query ok, 0 rows affected (0.00 sec)

records: 0 duplicates: 0 warnings: 0

小結:

1、只有innodb才能支援外來鍵

2、公共欄位的名字可以不一樣,但是資料型別要一樣

1.5.4 三種外來鍵操作

1、 嚴格限制(參見主表和從表)

2、 置空操作(set null):如果主表記錄刪除,或關聯字段更新,則從表外來鍵字段被設定為null。

3、 級聯操作(cascade):如果主表記錄刪除,則從表記錄也被刪除。主表更新,從表外來鍵字段也更新。

語法:foreign key (外來鍵字段) references 主表名 (關聯字段) [主表記錄刪除時的動作] [主表記錄更新時的動作]。

一般說刪除時置空,更新時級聯。

drop table if exists stuinfo;

create table stuinfo(

id tinyint primary key comment '學號,主鍵',

name varchar(20) comment '姓名'

)engine=innodb;

drop table if exists stuscore;

create table stuscore(

id int auto_increment primary key comment '主鍵',

sid tinyint comment '學號,外來鍵',

score tinyint unsigned comment '成績',

foreign key(sid) references stuinfo(id) on delete set null on update cascade

)engine=innodb;

小結:

置空、級聯操作中外鍵不能是從表的主鍵

Mysql資料庫完整性

一 資料完整性的概念 1 目的 為了防止不符合規範的資料進入資料庫,在使用者對資料進行插入 修改 刪除等操作時,dbms自動按照一定的約束條件對資料進行監測,使不符合規範的資料不能進入資料庫,以確保資料庫中儲存的資料正確 有效 相容。2 概念 約束是用來確保資料的準確性和一致性。資料的完整性就是對資...

資料庫 資料完整性

更安全的資料型別可參考 型別 位元組大小 有符號範圍 sigened 無符號範圍 unsigned tinyint 1 128 127 0 255 smallint 2 32768 32767 0 65535 mediumint 3 8388608 8388607 0 16777215 int in...

資料庫完整性

完整性約束條件 實體完整性給出了主鍵的取值的最低約束條件 規則是 主鍵的各個屬性都不能為空。參照完整性給出了在關係之間建立正確的聯絡的約束條件 規則是 外來鍵或者取空值 此時要求外來鍵的各個屬性均為空值 或者等於被參照關係中的主鍵的某個值。使用者自定義完整性 關係數控應用系統中的關係往往還應該滿足一...