本章为数据库主从表创建、删除等相关操作:
主键:primary key
外键:foreign key [ForeignFieldName] references PrimaryTableName([PrimaryFieldName])
规则:
①. 主外键关联后,如要执行删除主表,必须先删除从表;
②. 添加从表外键之前,必须先添加主表主键。
关键词:primary、foreign、references、auto_increment
1. 创建主表主键:
create table [TableName] ([FieldName Type Property])charset utf8;
示例:create table testTable (c_id int primary key)charset utf8;
2. 创建从表外键:
create table [TableName] ([FieldName Type Property])charset utf8;
示例:create table testTable1 (
u_id int not null,
u_cid int,
foreign key u_cid references testTable(c_id)
)charset utf8;
3. 删除从表外键:
alter table [TableName] drop foregin key [FieldName];
示例:alter table testTable drop foreign key u_cid;
4. 删除主表主键:
alter table [TableName] drop primary key;
示例:alter table testTable drop primary key;
5. 如何查看从表外键名称?
show create table [ForeignTableName];
示例:show create table testTable;
CONSTRAINT后面的就是外键名称,如“student_idfk_1”。
6. 添加主表主键:
alter table [PrimaryTableName] add primary key [PrimaryFieldName];
示例:alter table testTable add primary key c_id;
7. 添加从表外键:
alter table [ForeignTableName] add foreign key [ForeignTableFieldName] references [PrimaryTableName](PrimaryTableFieldName);
示例:alter table testTable1 add foreign key u_cid references testTable(c_id);
8. 设置主键自增:
create table [PrimaryTableName](FieldName Type Property)charset utf8;
示例:create table testTable (
c_id int primary key auto_increment
)charset utf8;
注释:auto_increment,只能和primary key一起使用。
上一章:MySQL数据库篇2
下一章:MySQL数据库篇4
网友评论