概念:對錶中的數據進行限定,保證數據正確、有效性和完整性。
分類:
- 主鍵約束:primary key
- 非空約束:not null
- 唯一約束:unique
- 外鍵約束:foreign key
-- 創建表時約束
create table stu(
id int,
name varchar(20) not null --name爲非空
);
--刪除name的非空約束
alter table stu modify name varchar(20);
-- 創建表之後添加非空約束
alter table stu modify name varchar(20) not null;
唯一約束可以使null,並且null與null之間不相等;
-- 唯一約束
create table stu(
id int,
phone_number varchar(20) unique -- 添加唯一約束
);
alter table stu modify phone_number varchar(20) ;-- 這樣無法刪除唯一約束
alter table stu drop index phone_number ;
-- 在創建表之後,添加唯一約束
alter table stu modify phone_number varchar(20) unique;
主鍵約束:非空且唯一,一張表只有一個字段爲主鍵;
create table stu(
id int primary key,
name varchar(20)
);
-- 刪除主鍵
-- 錯誤:alter table stu modify id int;
alter table stu drop primary key;
-- 添加主鍵錢要刪除重複id
alter table stu modify id int primary key;
自動增長:如果某一列是數值類型,使用關鍵字auto_increment 可以來完成值得自動增長
create table stu(
id int primary key auto_increment,
name varchar(20)
)
-- 自動增長的屬性可以輸入null,會自動讀取上一條數據並且加一
insert into stu values(null,'ccc');
insert into stu values(10,'ccc');
-- 自動增長只跟上一條記錄的數據有關係
insert into stu values(null,'ccc');
-- 刪除自動增長
alter table stu modify id int;
alter table stu modify id int auto_increment;
外鍵約束
1、在創建表時,可以添加外鍵
create table emp(
id int primary key auto_increment,
name varchar(30),
age int,
dep_name varchar(30),
dep_location varchar(30)
);
insert into emp (name,age,dep_name,dep_location) values('王禮陽',22,'王部','老王家');
insert into emp (name,age,dep_name,dep_location) values('王明陽',122,'王部','老王家');
insert into emp (name,age,dep_name,dep_location) values('朱元璋',666,'明部','老朱家');
insert into emp (name,age,dep_name,dep_location) values('朱棣',656,'明部','老朱家');
-- 外鍵
create table 表名(
constraint 外鍵名稱 foreign key 外鍵列名稱 references 主表名(主表列名城)
);
表的拆分:
-- 部門表
create table department(
id int primary key auto_increment,
dep_name varchar(20),
dep_location varchar(20)
);
-- 員工表
create table employee(
id int primary key auto_increment,
name varchar(20),
age int,
dep_id int,
constraint emp_dept_fk foreign key (dep_id) references(id)
);
insert into department values(null,'王部','老王家'),(null,'明部','老朱家');
insert into employee(name,age,dep_id) values ('王禮樣',20,1);
-- 刪除外鍵
alter table employee drop foreign key emp_dept_fk;
-- 添加外鍵
alter table employee add constraint emp_dept_fk(自己取得名字) foreign key (dep_id) references department(id)主表名稱(主表列名稱);
級聯操作
-- 添加外鍵,設置級聯更新和級聯刪除
alter table employee add constraint emp_dept_fk foreign key
(dep_id) references department(id) on update cascade on delete cascade;