2 数据库的约束

发布时间:2026/7/9 1:06:33
2 数据库的约束 1. 主键约束primary key主键的约束标识表中的一行数据当前指定的主键列的值不可以重复并且不能为NULLcreatetablestudent(student_idbigintprimarykeycomment学员编号,student_namevarchar(32)comment学员名称,student_genderchar(1)comment学员性别,student_birthdaydatecomment学员生日)comment学生表;insertintostudentvalues(1,李四,男,2001-11-11);Ps一般推荐给表添加一个主键约束一般情况下可以针对有意义数据设置主键约束。如果是单表够用建议直接使用逐渐自增性能最佳createtablestudent(student_idbigintprimarykeyauto_incrementcomment学员编号,student_namevarchar(32)comment学员名称,student_genderchar(1)comment学员性别,student_birthdaydatecomment学员生日,student_phonevarchar(11)uniquecomment学员手机号)comment学生表;insertintostudentvalues(NULL,李四,男,2001-11-12,18888888855);2. 唯一约束unique 唯一约束。标识表中的一行数据当前指定的唯一约束的列的值不允许重复可以为NULL允许该列存在多个NULLcreatetablestudent(student_idbigintprimarykeycomment学员编号,student_namevarchar(32)comment学员名称,student_genderchar(1)comment学员性别,student_birthdaydatecomment学员生日,student_phonevarchar(11)uniquecomment学员手机号)comment学生表;3. 非空约束not null在列的后面指定上这个约束即可createtablestudent(student_idbigintprimarykeyauto_incrementcomment学员编号,student_namevarchar(32)comment学员名称,student_genderchar(1)comment学员性别,student_birthdaydatenotnullcomment学员生日,student_phonevarchar(11)uniquecomment学员手机号)comment学生表;4. 默认值约束default 默认值当前列如果没有指定任何的值会采用这个默认值填充给学员名称列设置默认值如果没指定姓名就叫 ‘张三’。createtablestudent(student_idbigintprimarykeyauto_incrementcomment学员编号,student_namevarchar(32)default张三comment学员名称,student_genderchar(1)comment学员性别,student_birthdaydatenotnullcomment学员生日,student_phonevarchar(11)uniquecomment学员手机号)comment学生表;测试sqlinsertintostudent(student_gender,student_birthday,student_phone)values(男,2011-11-11,18888888433);5. 检查约束check (检查约束要求)这个是MySQL8.x提供的约束功能约束某一个列的值满足一定的条件要求给student表中的性别字段指定一个检查约束要求添加的值只能是男、女。不允许添加其他内容。-- 单独指定createtablestudent(student_idbigintprimarykeyauto_incrementcomment学员编号,student_namevarchar(32)default张三comment学员名称,student_genderchar(1)comment学员性别,student_birthdaydatenotnullcomment学员生日,student_phonevarchar(11)uniquecomment学员手机号,constraintstudent_gender_checkcheck(student_gender男orstudent_gender女))comment学生表;-- 在字段后直接编写。createtablestudent(student_idbigintprimarykeyauto_incrementcomment学员编号,student_namevarchar(32)default张三comment学员名称,student_genderchar(1)check(student_gender男orstudent_gender女)comment学员性别,student_birthdaydatenotnullcomment学员生日,student_phonevarchar(11)uniquecomment学员手机号)comment学生表;6. 数值的约束UNSIGNED数值的约束保证这个数值必须是正数不允许存储负数。同时取值范围还可以增加接近一倍。比如tinyint存储范围是-128到127如果追加上了UNSIGNED就可以标识0到255。# 添加unsigned约束后数值就不允许存储负数了。createtableyyy(idtinyintunsigned);insertintoyyyvalues(-1);