表的约束

    真正约束字段的是数据类型,但是数据类型约束很单一,需要有一些额外的约束,更好的保证数据的合法性,从业务逻辑角度保证数据的正确性。比如一个人的身份证号,要求是唯一的。

null/not null, default, comment, zerofill,primary key, auto_increment, unique key

1、空属性

    null、not null

            在建表的时候跟在字段后面,一把不为空

2、默认值

    default

            在建表的时候跟在字段后面,如果插入数据的时候没有赋值,就使用默认值

3、列描述

    comment

          在建表的时候跟在字段后面,用于描述字段

4、零填充

    zerofill    

  • 设置零填充--alter table student change id ID int(5) zerofill;

                    如果宽度小于设定的宽度(这里设置的是5),自动填充0。

  • 使用hex函数查看--select id hex(id) from student;

5、主键    

    primary key--不能为空;不能重复;一张表最多只能有一个主键;一般主键所在列通常是整数类型

  • 设置主键--alter table student add primary key(id);

                       在建表的时候跟在字段后面---id int primary key

                       在所有字段之后重新定义主键---primary key(id, name)

  • 删除主键--alter table student drop primary key;

6、 自增长

    auto_increment    当对应的字段,不给值,会自动的被系统触发,系统会从当前字段中已经有的最大值+1操作,得到一个新的不同的值。通常和主键搭配使用,作为逻辑主键。

    

建完表AUTO_INCREMENT 建完表添加默认值约束_字段

                    一般在建表的时候跟在主键后面---id int primary key auto_increment,批量插入获取的是第一个值

  • 查看自增长的程度--last_insert_id();

7、唯一键

    unique--不能重复;可以为空;一张表可以建立多个唯一键;

                     在建表的时候跟在主键后面---name varchar(10) unique,空字段不做唯一性比较

8、外键

    foreign key .. references ..

    外键用于定义主表和从表的关系:外键约束主要定义在从表上,主表则必须是有主键约束或unique约束。当定义外键后,要求外键列数据必须在主表的主键列存在或为null。

  • 先建主表,再建从表
  • 设置外键--foreign key(cno) references student(sno);

   

建完表AUTO_INCREMENT 建完表添加默认值约束_字段_02

create table if not exists goods( 

goods_id int primary key auto_increment comment '商品编号', 

goods_name varchar(10) not null comment '商品名称', 

unitprice float(7, 2) not null default 0 comment '商品单价',

category varchar(10) comment '商品类别', 

provider varchar(10) not null comment '供应商'

);
create table if not exists customer( 

customer_id int primary key auto_increment comment '客户id号', 

customer_name varchar(10) not null comment '客户姓名', 

address varchar(10) unique comment '客户邮箱', 

sex enum('男', '女') default '男' comment '客户性别', 

card_id char(10) unique comment '客户身份证号码'

);
create table if not exists purchase( 

order_id int primary key auto_increment comment '购买订单号', 

customer_id int not null comment '客户编号', 

goods_id int not null comment '商品号', 

nums int not null default 0 comment '购买数量', 

foreign key(customer_id) references customer(customer_id), 

foreign key(goods_id) references goods(goods_id) 

);