表的约束主要有:null/not null、default、comment、zerofill、primary key、auto_increment、unique key
一、空属性
- 两个值:null(默认)和not null
- 默认null,但是在实际场合中null不可以参与运算,所以我们需要加一些限制条件。
二、默认值(default)
默认值:有时某一个值经常出现,所以我们可以设定默认值。在需要修改,用户可以直接修改。
三、列描述(comment)
列描述:没有实际意义,用来专门描述字段是什么,就好比我们给一个小孩起名字一样。
四、zerofill
当我们执行语句desc table_name时,可以看到整形字段后面括号里面有一个数字,那么这个数字是什么呢?当没有zerofill属性时,括号内的数字是毫无意义的。
具体的括号内的数字我们可以自定义
五、主键(primary key)
主键:用来唯一的约束元组内的字段,不能重复,也不可以为空,一张表最多一个主键,主键一般都是整形。主键可以是单独一个字段,也可以是几个字段组成的复合主键。
- 在创建表的时候指定主键
- 使用primary key创建复合主键
- 表创建好了,也可以追加主键
alter table table_name add primary key(主键);
- 删除主键
alter table table_name drop primary key;
六、自增长(auto_increment)
auto_increment:当对应的字段,不给值,会自动的被系统触发,系统会从当前字段中已经有的最大值+1操作,得到一个新的不同的值。通常和主键搭配使用,作为逻辑主键。
自增长的特点:
- 任何一个字段要做自增长,前提是本身是一个索引(key一栏有值)
- 自增长字段必须是整数
- 一张表最多只能有一个自增长
七、唯一键(unique)
一张表中有往往有很多字段需要唯一性,数据不能重复,但是一张表中只能有一个主键:唯一键就可以解决表中有多个字段需要唯一性约束的问题。
唯一键的本质和主键差不多,唯一键允许为空,而且可以多个为空,空字段不做唯一性比较。
unique和primary key比较:唯一键不允许重复,但可以为空,主键既不能为空,也不能重复。
八、外键(foreign key)存储引擎必须是innoDB
外键用于定义主表和从表之间的关系:外键约束主要定义在从表上,主表必须是主键约束或者unique约束。当定义外键之后,要求外键列数据必须在主表的主键列存在或者为空。
foreign key (字段名) references 主表(列)
- 先创建主表
create table myclass (
id int primary key,
name varchar(30) not null comment'班级名'
);
- 后创建从表
create table stu (
id int primary key,
name varchar(30) not null comment '学生名',
class_id int,
foreign key (class_id) references myclass(id)
);
综合案例:
有一个商店的数据,记录客户及购物情况,有以下三个表组成:
- 商品goods(商品编号goods_ id,商品名goods_ name, 单价unitprice, 商品类别category, 供应商provider)
- 客户customer(客户号customer_ id,姓名name,住址address,邮箱email,性别sex,身份证card_id)
- 购买purchase(购买订单号order_ id,客户号customer_ id,商品号goods_ id,购买数量nums)
要求:
- 每个表的主外键
- 客户的姓名不能为空值
- 邮箱不能重复
- 客户的性别(男,女)
create table goods(
goods_id int unsigned primary key comment '商品编号',
goods_name varchar(30) not null comment '商品名',
unitprice decimal(10,2) not null default 0.00 comment '单价',
category smallint not null default 0 comment '商品类别',
provider varchar(30) not null default ''
);
create table customer(
customer_id int unsigned primary key comment '客户号' auto_increment,
name varchar(20) not null,
address varchar(40) not null,
email varchar(60) unique not null,
sex enum('男','女') default '男' not null,
card_id varchar(20) not null unique
);
create table purchase(
order_id int unsigned auto_increment primary key,
customer_id int unsigned not null,
goods_id int unsigned not null,
nums int unsigned not null default 0,
foreign key(customer_id) references customer(customer_id),
foreign key(goods_id) references goods(goods_id)
);