MySQL完整性约束

not null 与default

create table tb1(
    nid int not null defalut 2,
    num int not null

);

unique

#第一种创建unique的方式
#例子1:
create table department(
    id int,
    name char(10) unique
);
mysql> insert into department values(1,'it'),(2,'it');
ERROR 1062 (23000): Duplicate entry 'it' for key 'name'

#例子2:
create table department(
    id int unique,
    name char(10) unique
);
insert into department values(1,'it'),(2,'sale');

#第二种创建unique的方式
create table department(
    id int,
    name char(10) ,
    unique(id),
    unique(name)
);
insert into department values(1,'it'),(2,'sale');

#联合唯一
create table services(
        id int,
        ip char(15),
        port int,
        unique(id),
        unique(ip,port)
       );

primary key

在MySQL的一个表中只有唯一的一个主键,不能有多列主键,但可以有复合主键

一个表中可以:

单列做主键
多列做主键(复合主键)

约束:等价于 not null unique,字段的值不为空且唯一

存储引擎默认是(innodb):对于innodb存储引擎来说,一张表必须有一个主键。

# 创建t14表,为id字段设置主键,唯一的不同的记录
create table t14(
    id int primary key,
    name char(16)
);

复合主键
create table t16(
ip char(15),
port int,
primary key(ip,port)
);

auto_increment

约束:约束的字段为自动增长,约束的字段必须同时被key约束

foreign key

#1.创建表时先创建被关联表,再创建关联表
# 先创建被关联表(dep表)
create table dep(
    id int primary key,
    name varchar(20) not null,
    descripe varchar(20) not null
);

#再创建关联表(emp表)
create table emp(
    id int primary key,
    name varchar(20) not null,
    age int not null,
    dep_id int,
    constraint fk_dep foreign key(dep_id) references dep(id) 
);

#2.插入记录时,先往被关联表中插入记录,再往关联表中插入记录

insert into dep values
(1,'IT','IT技术部门'),
(2,'销售部','销售部门'),
(3,'财务部','花钱部门');

insert into emp values
(1,'qwe',18,1),
(2,'asd',19,1),
(3,'zxc',20,2),
(4,'ert',40,3),
(5,'dfg',18,2);

3.删除表
#按道理来说,删除了部门表中的某个部门,员工表的有关联的记录相继删除。
mysql> delete from dep where id=3;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`db5`.`emp`, CONSTRAINT `fk_name` FOREIGN KEY (`dep_id`) REFERENCES `dep` (`id`))

#但是先删除员工表的记录之后,再删除当前部门就没有任何问题

在建表的时候还有个很重要的内容,叫同步删除,同步更新

接下来将刚建好的两张表全部删除,先删除关联表(emp),再删除被关联表(dep)

接下来:
重复上面的操作建表
注意:在关联表中加入
on delete cascade #同步删除
on update cascade #同步更新

create table emp(
    id int primary key,
    name varchar(20) not null,
    age int not null,
    dep_id int,
    constraint fk_dep foreign key(dep_id) references dep(id) 
    on delete cascade #同步删除
    on update cascade #同步更新
);
再去删被关联表(dep)的记录,关联表(emp)中的记录也跟着删除
原文地址:https://www.cnblogs.com/NachoLau/p/10398476.html