数据库约束

数据库约束

约束类型:

  • NOT NULL ----指示某列不能存储 NULL 值。
  • UNIQUE ----- 保证某列的每行必须有唯一的值。
  • DEFAULT ----- 规定没有给列赋值时的默认值。
  • PRIMARY KEY ----- NOT NULL 和 UNIQUE 的结合。确保某列(或两个列多个列的结合)有唯一标识,有助于更容易更快速地找到表中的一个特定的记录。
  • FOREIGN KEY ----- 保证一个表中的数据匹配另一个表中的值的参照完整性。
  • CHECK ----- 保证列中的值符合指定的条件。对于MySQL数据库,对CHECK子句进行分析,但是忽略 CHECK子句。

NULL约束

创建表时,可以指定某列不为空

drop table if exists student;
create table student(
     id int ,
     sn int,
     name varchar(20) not null,
     qq_mail varchar(20)
);

在这里插入图片描述

UNIQUE :唯一约束

指定sn列是唯一的,不重复的

drop table if exists student;
create table student(
     id int not null;
     sn int unique,
     name varchar(20),
     qq_mail varchar(20)
);

DEFAULT:默认值约束

指定插入数据时,name列为空,默认值为unkown

drop table if exists student;
create table student(
     id int not null;
     sn int unique,
     name varchar(20) default 'unkown',
     qq_mail varchar(20)
);

PRIMARY KEY:主键约束

指定id列为主键

drop table if exists student;
create table student(
     id int not null primary key;
     sn int unique,
     name varchar(20),
     qq_mail varchar(20)
);

对于整数类型的主键,常搭配自增长auto_increment来使用,插入数据对应字段不给值时,使用最大值+1.
primary key 主键约束:它是NOT NULL和UNIQUE的结合。也就是说,当一个字段被PRIMARY KEY 修饰后,那么这个 字段就是不能为空且是独一无二的!!! 因为是独一无二的,所以,一般搭配:auto_increment;

id int primary key auto_increment,

当创建好表之后,表中没有任何的数据,当第一次执行插入的时 候,当前主键,也就是ID,会自动从1开始。

在这里插入图片描述
当我将刚刚插入的数据删除后,再次进行插入的时候,就会在原来的基础,也就是上一次最后插入的语句的ID上开始加1;
在这里插入图片描述
只有当你把整个表都删除了,那么当你再次插入的时候,才是从1开始的!!!

alter 可以修改字段的类型

alter table table_ name add clumom字段名类型;

外键约束

外键用于关联其他表的主键或唯一键,语法:

foreign key(字段名)references 主表(列)

例子:创建班级表classes,id为主键
创建班级表,有使用MySQL关键字作为字段时,需要使用``来标识

drop table if exists classes;
create table classes(
id int primary key auto_increment,
name varchar(20),
`desc` varchar(200)
);

创建学生表student,一个学生对应一个班级,一个班级对应多个学生。使用id为主键,
classes_id为外键,关联班级表id

drop table if exists student;
create table student(
id int primary key auto_increment,
sn int unique,
name varchar(20) default 'unkown',
qq_mail int,
classes_id int,
foreign key(classes_id) references classes(id)
);

CHECK约束

drop table if exists test_user; 
create table test_user ( 
id int, 
name varchar(20), 
sex varchar(1), 
check (sex ='男' or sex='女') );

将来在插入数据的时候,只能插入sex为男或者女。

两张表的各种操作

现在我们有2张表,一张班级表,一张学生表。
建表:先创建主表
插入数据:先插入主表
删除数据:先删除哪张表的数据??? 先删除子表。但是,删除主表也是可以的,前提是主表当中的这个id没有被关联。 如果被关联了,那么就会失败

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值