mysql笔记之约束

 

概念:对表中的数据进行限定,保证数据正确、有效性和完整性。

分类:

  1. 主键约束:primary key
  2. 非空约束:not null    
  3. 唯一约束:unique
  4. 外键约束: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;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章