约束

约束

单词 作用
not null 约束某一个字段,不能为空
unsigned 无符号的,约束字段不能为负,如果是负默认改为0
default '默认值' 给某个字段添加默认值默认值
unique 值不能重复,但是可以写入多个null,联合唯一
auto_increment 只能对数字有效,自带非空约束,至少是unique约束后才能使用auto_increment
primary key 第一个被定义为非空+唯一的那一列会成为这张表的主键(primary key),也可以直接使用primary key定义主
  • 联合唯一的使用方法
create table s1(id int unique not null,gender enum('男','女') default'男',family char(18),name char(18),unique(family,name));

问题:在使用not null 的情况下 使用insert into t3(id) values(1)这种情况下,任然会有空数据:

  • 解决方法:

    • 设置严格模式

      1. 直接在mysql中生效(重启失效)

        set sql_mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION";
        
      2. 配置文件中添加

        sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
        
  • 主键

    1.主键为了保证表中的每一条数据的该字段都是表格中的唯一值。换言之,它是用来独一无二地确认一个表格中的每一行数据。主键可以包含一个字段或多个字段。当主键包含多个栏位时,称为组合键,也可以叫联合主键。
    2.主键可以在建置新表格时设定 (运用 CREATE TABLE 语句),或是以改变现有的表格架构方式设定 (运用 ALTER TABLE)。
    3.主键必须唯一,主键值非空;可以是单一字段,也可以是多字段组合。

    • 第一个被定义为非空+唯一的那一列会成为这张表的主键(primary key),也可以直接使用primary key定义主键
    • 一张表只能定义一个主键

微信图片_20210831105014

  • 联合主键
create table s1(id int unique not null,gender enum('男','女') default'男',family char(18),name char(18),primary key(family,name));
  • 自增(auto_increment)

    • auto_increment只能对数字有效,自带非空约束

    • 至少是unique约束后才能使用auto_increment

    #自增的使用方法
    create table v6(id int primary key auto_increment,name char(18));
    #在表中有自增时必须使用以下方法插入数据,自增第1个默认为1
    insert into v6(name) values('xiaowang');
    
  • 外键

    • 格式
    Foreign key(自己的字段) references 外表(外表的字段) on update cascade on delete cascade
    注:外表的字段必须至少是唯一的
    
    • 实例
    #班级表
    create table class(cid int primary key auto_increment,
                       class_name varchar(6) unique);
    #学生表
    create table student(id int primary key auto_increment,
                         name varchar(6) not null,
                         gender enum('男','女') default'男',
                         class_name varchar(6) not null,
                         Foreign key(class_name) references class(class_name) on update cascade on delete cascade);
    
    #on update cascade   及时更改 
    #on delete cascade	 及时删除
    
    
posted @ 2021-12-14 17:19  刘家小仙女  阅读(68)  评论(0编辑  收藏  举报