• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
珍珠奶茶不加糖
博客园    首页    新随笔    联系   管理    订阅  订阅
MySQL常见约束

MySQL常见约束

MySQL常见约束

约束条件

  • 非空约束: not null
  • 保证字段的值不能为空
  •  
  • 默认约束: default
  • 保证字段在没有输入任何值的时候会自动添加一个默认值
  •  
  • 唯一约束: unique
  • 保证插入数据的唯一性,不可重复,但是可以为空
  •  
  • 检查约束(MySQL不支持): check
  •  
  • 主键约束: primary key
  • 唯一且非空
  •  
  • 外键约束: froeign key
  • 用于限制两个表的关系,保证表A该字段的值来自于主表B相关联的字段的值,多用于多表查询
  •  
  • 前五种 语法: constraint 约束名 约束类型(字段名称)
  • 外键 语法: constraint 约束名 约束类型(字段名称) foregin key(字段名称)references 关联表名(字段名)
  • 举例
 create table students(
    id int(10),
    name varchar(20) not null, //非空约束
    sex char(1) default '男', //默认约束
    seat int(10),
    age int(3),
    teacher_id int(10),
    constraint pk_id primary key(id), //主键
    constraint uq unique(seat), //唯一
    constraint ck check(sex='男' or sex = '女'), //检查 MySQL不支持,写了不报错,但是没效果
    constraint fk_students_teacher_id foreign key(teacher_id) references tb_teacher(id) //外键
)

 

MySQL添加或删除约束

  • 删除约束语法 alter table 表名 drop constraint 约束名称
  • 非空
    • 添加: alter table tb_students modify column account varchar(20) not null
    • 删除: alter table tb_students modify column account varchar(20)
  • 默认
    • 添加: alter table tb_students moodify column age int default 18
    • 删除: alter table tb_students modify column age
  • 唯一
    • 添加: alter table tb_students modify column seat int unique
    • 删除: alter table tb_students drop index seat
  • 主键
    • 添加: alter table tb_students modify column id int primary key
    • 删除: alter table tb_students drop primary key
  • 外键
    • 添加: alter table tb_students add foreign key(tb_teacher_id) references tb_teacher(id)
    • 删除: alter table tb_students drop foreign key fk_students_teacher

自增长列

  • auto_increment
  • 一个表有且只能有一个自增长列,自增长列一般与主键搭配
  • 修改表添加自增常列: alter table tb_user modify column id int primary key auto_increment
  • 删除自增长列: alter table tb_user modify column id int
如有问题,请发送邮件至buxiaqingcheng@163.com或者buxiaqingcheng@dingtalk.com
posted on 2020-06-08 17:28  珍珠奶茶不加糖  阅读(160)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3