MySQL关于表的约束

在这一小节中主要讲述数据库中的一些约束:null/not null,default,comment,zerofill,primary key,auto_increment,unique key.
1.空属性
在数据库中我们的默认字段是null,但是在实际中我么却很少用null,因为null是无法参与实际运算的。
2.默认值
对于默认值的使用需要我们注意的地方是当表中有null值的时候我们就不能将默认值设置为null了,因为这样就分不清到底null值是默认的还是原本的。
3.列描述
列描述就是在创建的时候我们在创建语句里面加入的注释,可以知道我们创建的到底是什么。
4.主键
primary key用来唯一的约束该字段里面的数据,不能重复、不能为空、一张表中最多只能有一个主键;
注意:主键所在的列通常是整数类型。
在创建表的时候,在所有字段之后使用primary key 来创建主键
5.自增长
自增长需要注意的是:任何一个字段要作自增长,前提是本身是一个索引(key一栏有值)、自增长字段必须是整数、一张表最多只能有一个自增长。
6.唯一键:unique key
虽然主键可以满足唯一性的要求,但是一个表中只能满足只有一个主键,当有很多个字段需要唯一性时,就不能满足我们的需要了,所以我们有了唯一键,唯一键可以使得该字段的数据是不能重复的.一个表中可以有多个唯一键。
7.外键:foreign key (从表中的一个性质) references 主表(主表中与从表中关联的性质)
外键用于定义主表和从表之间的关系:而外键约束主要用于定义在从表上,主表则必须是有主键约束或unique约束的。当定义外键后,要求外键 列数据必须在主表的主键列或者唯一列存在或者为null。
对于这些约束性质的一个综合案例:
有一个商店的数据,记录客户及购物情况,有以下三个表组成:
。商品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)
要求:
。每个表的主外键
。客户的姓名不能为空
。邮箱不能重复
。客户的性别(男,女)
SQL:
–创建数据库表
–表goods在整个里面相当于是主表
create database shopping;
create table goods(
goods_id int not null primary key auto_increment comment ‘商品号’,–用主键修饰以后最好不要用默认值修饰
goods_name varchar(30) not null default ‘’ comment ‘商品名’,
unitprice int not null comment ‘单价,单位分’,
category varchar(30) not null comment ‘商品类别’,
provider varchar(30) not null comment ‘供应商’
);
–表 customer也是主表
create table customer (
customer_id int not null primary key auto_increment comment ‘客户号’,
name varchar(30) not null default ‘’ comment ‘客户姓名’,
address varchar(256) not null comment ‘住址’,
email varchar(30) not null unique key comment ‘邮箱’,
sex enum(‘男’,‘女’) not null default ‘男’ comment ‘性别’,
card_id char(18) not null comment ‘身份证号码’
);
–它是相对于 goods和customer的从表与主表的goods_id 和 customer_id相关联,所以需要用到外键
–一个表里面只能有一个自增长
create table purchase(
order_id int not null primary key auto_increment comment ‘购买订单号’,
customer_id int not null unique key comment ‘客户号’,
goods_id int not null unique key comment ‘商品号’,
nums int default 0 comment ‘购买数量’,
foreign key (customer_id) references customer(customer_id),
foreign key (goods_id) references goods(goods_id)
);

猜你喜欢

转载自blog.csdn.net/ZhuiZhuDream5/article/details/83504842
今日推荐