数据表中的列属性(也称列约束)
详细可以在mysql客户端控制台中使用 help create table; 命令来查看!!!
1.Reference(关联)
a) 一对一关联:典型设计方案--->两个实体表内存在相同的主键字段,即一个关系的主键值等于另一个关系中的主键值(垂直分割)。一般情况下,一个表中的字段过多,就应该做垂直分割,这些分割成的关系之间都是一对一的关系。
b) 一对多关联:在“多”的一端进行外键维护。
c) 多对多关联:利用一个中间表表示两个实体之间的关系。组合主键,分别来自两个实体表中的主键。
d) Foreign key(外键)
i. 作用: 约束处于关系内的实体; 增加子表(含外键的表)记录时,是否有与之对应的父表(被子表指向的表)记录;在删除或更新主表记录时,子表应该如何处理相关的记录。
ii. 定义外键的方法:
Create table student
(
Id int auto_increment primary key,
Class_id int not null,
Name varchar(20) not null comment ‘学生姓名’,
Age int default 20,
Foreign key (class_id) references t_class(id)
);
iii. 设置级联操作(主表数据改变时,与之关联的从表数据应该如何操作)。允许的级联动作:1.cascade关联操作,如果主表被更新或删除,从表也会执行相应的动作;2.set null, 表示从表不指向主表任何记录,当主表中的主键改变时,将从表中的外键设为null; 3.restrict:拒绝主表的相关操作,即不让操作主表对应记录。注意:级联操作是在外键表上定义外键时约定的!
1.主表更新。
2.主表删除。
例:
Create table student
(
Id int auto_increment primary key,
Class_id int not null,
Name varchar(20) not null comment ‘学生姓名’,
Age int default 20,
Foreign key (class_id) references t_class(id)
on delete set null
on update cascade
//表示主表记录被删除后,从表中对应的外键被设置为null; 主记录更新时,从表对应外键也更新
);
2.Default value(字段默认值)
3.Primary key | Unique key(主索引 | 唯一索引)
a) 主键可以是真实实体的属性,但是常用的好的解决方案是:使用一个与实体信息不相关的属性,这样不会与业务逻辑产生任何关系,只用于标志记录。
b) 主键两种设置语法
i. 字段上设置。
例如:Create table student
(
id int auto_increment primary key,
Name varchar(20)
);
ii. 定义玩所有字段后再定义(这种方式可以用于定义组合主键)。
Create table student
(
Id int auto_increment,
Name varchar(20),
Primary key(id)
);
4.Auto_increment(自动增长)
5.Null | Not null(空于非空)
6.Comment(列注释)
例如: create table student
(
id int auto_increment primary key,
Name varchar(20) not null comment ‘学生姓名’
);