mysql-约束专题更新中。。
查看表的所有信息:show create table 表名;
添加主键约束:alter table 表名 add constraint 主键 (形如:PK_表名) primary key 表名(主键字段);
添加外键约束:alter table 从表 add constraint 外键(形如:FK_从表_主表) foreign key 从表(外键字段) references 主表(主键字段);
(alter table 主表名 add foreign key (字段 ) references 从表名(字段) on delete cascade)
添加唯一约束:alter table 表名 add unique key 约束名 (字段);
删除主键约束:alter table 表名 drop primary key;
删除外键约束:alter table 表名 drop foreign key 外键(区分大小写);
创建表:
表一:(主表)
create table company_about_constraint #这样命名表名主要是见名知意
(
company_id smallint not null,
company_name varchar(10) not null
);
表二:(从表)
create table company_foreign_about_constraint
(company_id smallint not null,
company_owner varchar(15) not null);
//创建主键约束
(1)alter table company_about_constraint add primary key(id);
(2)alter table company_about_constraint add constraint primary_k primary key(id);
再将主键列设为auto_increment:
alter table company_about_constraint modify id smallint auto_increment;
//删除主键约束
(1)alter table company_about_constraint drop primary key;
注意:删除主键约束的时候,如果主键已经是auto_increment型,则无法删除,因为只有键才能是auto_increment型的
约束名称可以用 show create table company_about_constraint 命令查看,可以用modify修改字段的属性,修改后则可以删除主键约束;
//创建外键约束
主键外键的数据类型、长短必须要保证一致性
(1)alter table company_foreign_about_constraint add foreign key(company_id) references company(company_id);
(2)alter table company_foreign_about_constraint add constraint k foreign key(company_id) references company_about_constraint(company_id);
//删除外键约束
(1)alter table company_foreign_about_constraint drop foreign key k;
删除外键时,如果外键有名字,必须要把名字一起删除;
主键(primary key) 能够唯一标识表中某一行的属性或属性组。一个表只能有一个主键,但可以有多个候选索引。主键常常与外键构成参照完整性约束,防止出现数据不一致。主键可以保证记录的唯一和主键域非空,数据库管理系统对于主键自动生成唯一索引,所以主键也是一个特殊的索引。
外键(foreign key) 是用于建立和加强两个表数据之间的链接的一列或多列。外键约束主要用来维护两个表之间数据的一致性。简言之,表的外键就是另一表的主键,外键将两表联系起来。一般情况下,要删除一张表中的主键必须首先要确保其它表中的没有相同外键(即该表中的主键没有一个外键和它相关联)。
//创建唯一约束
(1)alter table person add unique key(name);
(2)alter table person add constraint unique_k unique key(name);
//删除唯一约束
因为创建unique约束后,系统会自动给此列创建索引,用show create table table_name查看索引名称
alter table person drop index name;
mysql 主键索引和唯一索引区别

浙公网安备 33010602011771号