Mysql實驗(二)
阿新 • • 發佈:2019-02-07
一、實驗目的
1.掌握索引的使用方法;
2.掌握資料完整性的實現方法;
二、實驗內容
1.瞭解索引的作用與分類;
2.掌握索引的建立方法;
3.理解資料完整性的概念及其分類;
4.掌握各種資料完整性的實現方法;
三、實驗過程及結果
1.建立索引
(1)create index depart_ind
on Employees(DepartmentID);
(2)create index Ad_ind
on Employees(Name,Address);
(3)create unique index Dep_ind
on Departments(DepartmentName);
(4)檢視索引
show index from Employees;
show index from Departments;
(5)alter table Employees
add unique index date_ind(Birthday),
add index na_ind(Name,Sex);
(6)alter table Employees
add primary key(DepartmentID);
因為已經創立了主鍵,所以創建出錯,顯示主鍵已被創立;
(7)create table DepartmentS1
(
DepartmentID char(3),
DepartmentName char(20),
Note text,
primary key(DepartmentName),
index DID_ind(DepartmentID)
);
2.刪除索引;
(1)drop index depart_ind on Employees;
(2)alter table Departments
//drop primary key,
drop index Dep_ind;
3.資料完整性
(1)create table Employees3
(
EmployeeID char(6) not null,
Name char(10) not null primary key,
Sex tinyint(1),
Education char(4),
unique(EmployeeID)
);
(2)create table Salary1
(
EmployeeID char(6) not null primary key,
InCome float(8) not null,
OutCome float(8) not null,
foreign key(EmployeeID)
references Salary(EmployeeID)
on update cascade
on delete cascade
);
(3)create table students
(
學號 char(6) not null,
性別 char(1) not null,
check(性別 in (‘男’,’女’))
);
四、實驗總結
通過本實驗,學習到了索引是根據表中一列或者若干列按照一定順序建立的列值與記錄行之間的對應關係,可以用來快速讀取資料、保證資料記錄的唯一性、實行表與表之間的參照完整性、減少排序和分組的時間。給一個表新增索引的兩種方法,一種是使用CREATE INDEX語句新增,另一種是在建立表示使用index 關鍵字直接新增索引。索引又分為單列的普通索引,符合索引和符合索引三種,一個表可以同時使用多種索引方式;刪除索引也有兩種方式,使用DROP INDEX 語句和alter 與drop index 一起使用;資料的完整性可以用主鍵、外來鍵、check等方式來約束;
五、程式碼
/***1.建立索引*************/
create index depart_ind
on Employees(DepartmentID);
create index Ad_ind
on Employees(Name,Address);
create unique index Dep_ind
on Departments(DepartmentName);
show index from Employees;
show index from Departments;
alter table Employees
add unique index date_ind(Birthday),
add index na_ind(Name,Sex);
alter table Employees
add primary key(DepartmentID);
create table DepartmentS1
(
DepartmentID char(3),
DepartmentName char(20),
Note text,
primary key(DepartmentName),
index DID_ind(DepartmentID)
);
/************2.刪除索引*************/
drop index depart_ind on Employees;
alter table Departments
//drop primary key,
drop index Dep_ind;
/***************3.資料完整性***********/
create table Employees3
(
EmployeeID char(6) not null,
Name char(10) not null primary key,
Sex tinyint(1),
Education char(4),
unique(EmployeeID)
);
create table Salary1
(
EmployeesID char(6) not null primary key,
InCome float(8) not null,
OutCome float(8) not null,
foreign key(EmployeesID)
references Salary(EmployeesID)
on update cascade
on delete cascade
);
create table students
(
學號 char(6) not null,
性別 char(1) not null,
check(性別 in ('男','女'))
);