MySQL约束条件

1. 约束条件分类:

  • 主键约束:primary key:
    唯一约束 + 非空约束 的组合,可以同时保证唯一性和非空。

  • 外键约束:foreign key:
    用于限制两个表的关系,保证从表该字段的值来自于主表相关联的字段的值

  • 非空约束:not null :
    保证字段的值不能为空

  • 唯一约束:unique:
    保证唯一性但是可以为空,

  • 默认约束:default:
    保证字段总会有值,即使没有插入值,都会有默认值!

  • 自增长列:auto_increment:
    一个表中有且只能有一个自增长列

  • 检查性约束:check
    在MySQL已经不支持,语法不报错,但无效可以使用枚举类型替代:枚举类型(enum)

create table student(
studentno int auto_increment primary key , //定义学生学号为主键,设置位自增长
sname nvarchar(8) not null, //定义学生姓名为非空
sex nchar(1) default '男',  //定义性别,默认值为‘男’
birthday datetime null,     //定义出生日期,默认为null
classno nchar(6) ,          //定义所属教室号
phone nchar(11) unique,     //定义唯一约束
email nvarchar(30) unique,  //定义唯一约束
constraint fk_class         //给约束起名字
foreign key (classno) references class(classno) //将教室号设置为外键
);

2. 约束范围

  • 列级约束
create table student(
studentno int auto_increment primary key , 
sname nvarchar(8) not null
);
  • 表级约束
create table student(
studentno int auto_increment  , 
sname nvarchar(8) not null,
primary key(studentno,sname)
);
  • 表级约束可以给约束起名字,方便以后删除:
create table student(
studentno int auto_increment  , 
sname nvarchar(8) not null,
constraint pk_student primary key(studentno,sname)
);

3.修改约束

  • 主键 (primary key)
    添加:alter table 表名 add primary key(数据);
    修改:alter table 表名 modify column 列名 数据类型 primary key;
    删除:alter table 表名 drop primary key ;

  • 外键 (foreign key)
    添加:alter table 表名 add foreign key(列名) references 外键表名(外键列名);
    删除:alter table 表名 drop foreign key 外键约束名称;

  • 唯一 (unique)
    添加:alter table 表名 modify column 列名 数据类型 unique;
    删除:alter table 表名 drop index seat;
    查看:show index from 表名;

  • 其他
    添加:alter table 表名 modify column 列名 数据类型 约束条件;
    删除:alter table 表名 modify column 列名 数据类型 ;

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龙源lll

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值