约束
作用 对表中的数据进行进一步的限制, 保证数据的正确性, 有效性和完整性 种类 primary key : 主键约束 unique : 唯一约束 not null : 非空约束 default : 默认值 foreign key : 外键约束 auto_increment : 自增约束(适用于int数据类型)
主键约束
特点 注意事项 通常不用业务字段作为主键, 单独给每张表设计一个id的字段, 把id作为主键; 主键是给数据库和程序使用的, 不是给最终的客户使用的; 所以主键有没有含义没有关系, 只要不重复, 非空就行 每张表都应该有一个主键, 并且每张表只能有一个主键(可以一组字段作为一张表的主键)
1. 在创建表的时候给字段添加主键
create table 表名 ( 字段名 数据类型 primary key , 字段名 数据类型, 字段名 数据类型
) ;
create table 表名 ( 字段名1 数据类型, 字段名2 数据类型, 字段名3 数据类型, primary key ( 字段名1 , 字段名2 )
) ; 2. 在已有表中添加主键
alter table 表名 add primary key ( 字段名) ;
alter table 表名 add primary key ( 字段名1 , 字段名2 ) ;
自增约束(主键自增)
作用 能够设置主键 为自动增长 主键如果让我们自己添加很有可能重复, 我们通常希望在每次插入新记录时, 数据库自动生成主键字段的值 注意事项
create table test1 ( id int primary key auto_increment , name varchar ( 10 ) , age int
) ;
alter table test1 modify id int primary key auto_increment ;
alter table test1 modify id int auto_increment ;
默认值
create table test1 ( id int , name varchar ( 10 ) , age int default 18
) ; insert into test1( name, age) values ( '11' , null ) ;
insert into db4. test1( name) values ( '22' ) ;
表的关系和外键约束
表的关系分为一对一, 一对多和多对多, 在处理多对多关系时我们需要引入第三张表 , 作为多对多两张表的桥梁 第三张表需要引入其余两张表的主键 作为自己表中的外键
create table tb_order ( id int primary key auto_increment , payment double ( 10 , 2 ) , payment_type tinyint , status tinyint
) ; create table tb_goods ( id int primary key auto_increment , title varchar ( 100 ) , price double ( 10 , 2 )
) ; create table tb_order_goods ( id int primary key auto_increment , order_id int , goods_id int , count int
) ;
alter table 表名 add [ constraint 约束名称]
foreign key ( 当前表中的列名) references 被引用的表名( 被引用表的列名) ;
alter table tb_order_goods add constraint fk_order_id
foreign key ( order_id) references tb_order( id) ; alter table tb_order_goods add constraint fk_goods_id
foreign key ( goods_id) references tb_goods( id) ;
alter table tb_order_goods add
foreign key ( order_id) references tb_order( id) ; alter table tb_order_goods add
foreign key ( goods_id) references tb_goods( id) ;
create table tb_order_goods ( id int primary key auto_increment , order_id int , goods_id int , count int , constraint fk_order_id foreign key ( order_id) references tb_order( id) , constraint fk_goods_id foreign key ( goods_id) references tb_goods( id)
) ;
create table tb_order_goods ( id int primary key auto_increment , order_id int , goods_id int , count int , foreign key ( order_id) references tb_order( id) , foreign key ( goods_id) references tb_goods( id)
) ;
注意事项 添加数据需要先添加主表, 然后添加从表 删除数据需要先删除从表, 然后再删除主表