天天看點

mysql實體完整性實作方法_mysql資料庫 --資料完整性---實體完整性-域完整性-參照完整性...

一、資料完整性

資料完整性是為了保證插入到資料庫中的資料是正确的,防止使用者可能的錯誤輸入。

資料完整性分為實體完整性、域完整性、參照完整性。

2.1實體(行)完整性

(實體完整性中的實體指的是表中的行,因為一行記錄對應一個實體)

實體完整性規定表的一行在表中是唯一的實體,不能出現重複。

實體完整性通過表的主鍵來實作。

主鍵關鍵字: primary key

主鍵特點: 不能為null,并且唯一。

主鍵分類:

邏輯主鍵:例如ID,不代表實際的業務意義,隻是用來唯一辨別一條記錄(推薦)

業務主鍵:例如username,參與實際的業務邏輯。

主鍵使用方式:

方式一:

Create table t1(

Id int primary key,

Name varchar(100)

);

Insert into t1 values(1,’zs’);

Insert into t1 values(2,’ls’);

主鍵自動增長:

關鍵字: auto_increment

create table t4(

id int primary key auto_increment,

name varchar(100)

);

Insert into t4(name) values(‘zs’);

Insert into t4 values(null,’ls’);

2.2域(列)完整性

指資料庫表的列(即字段)必須符合某種特定的資料類型或限制

資料類型

長度

非空限制:NOT NULL

唯一限制:UNIQUE

CREATE TABLE t5(

username varchar(100) NOT NULL UNIQUE,

gender varchar(100) NOT NULL,

phonenum varchar(100) UNIQUE

);

2.3參照完整性

參照完整性指的就是多表之間的設計,主要使用外鍵限制。

多表設計**: 一對多、多對多、一對一設計**

2.3.1一對多(1* N)

1.客戶和訂單的關系就是一對多,一個客戶可以有多張訂單,一張訂單屬于一個客戶;

步驟:

(1).畫出客戶和訂單的表格

(2).畫出customer_id外鍵列,進行外鍵限制。

(3).代碼實作

2. 代碼實作:

建立客戶表:

CREATE TABLE customers(

id int,

name varchar(100),

address varchar(255),

PRIMARY KEY(id)

);

建立訂單表:

CREATE TABLE orders(

order_num int primary key,

price float(8,2),

status int,

customer_id int,

CONSTRAINT customer_id_fk FOREIGN KEY(customer_id) REFERENCES customers(id)

);

// 外鍵限制:

// constraint customer_id_fk foreign key(customer_id) references customers(id);

注: constraint: 限制的意思**。foreign key**: 外鍵。references: 參照

建立一個名叫customer_id_fk的外鍵限制,其中外鍵指的是**customer_id,**并且參照的是 customers表中的id列。

1.3.2多對多

老師和學生是多對多關系, 一個老師對應多個學生,一個學生被多個老師教多個學生

mysql實體完整性實作方法_mysql資料庫 --資料完整性---實體完整性-域完整性-參照完整性...

建立老師表:

Create table teachers(

id int,

name varchar(100)

salary float(8,2),

primary key(id)

);

建立學生表:

Create table students(

id int,

name varchar(100),

grade varchar(100),

primary key(id)

);

第三張表格:

Create table teacher_student(

t_id int,

s_id int,

primary key(t_id,s_id)

CONSTRAINT teacher_id_fk FOREIGN KEY(t_id) REFERENCES teachers(id),

CONSTRAINT student_id_fk FOREIGN KEY(s_id) REFERENCES students(id)

);

#主鍵primary key 的三種表達方式:

id int primary key

primary key(id)

alter table teachers add primary key(id)

1.3.3一對一

按照外鍵關聯

在表中的外鍵添加唯一限制

mysql實體完整性實作方法_mysql資料庫 --資料完整性---實體完整性-域完整性-參照完整性...

按照主鍵關聯

對主鍵添加外鍵限制

mysql實體完整性實作方法_mysql資料庫 --資料完整性---實體完整性-域完整性-參照完整性...