200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > mysql 外键关联_mysql外键关联

mysql 外键关联_mysql外键关联

时间:2024-01-03 05:36:28

相关推荐

mysql 外键关联_mysql外键关联

主键:是唯一标识一条记录,不能有重复的,不允许为空,用来保证数据完整性

外键:是另一表的主键, 外键可以有重复的, 可以是空值,用来和其他表建立联系用的。所以说,如果谈到了外键,一定是至少涉及到两张表。

创建外键的方式:

方式一:表已经创建好了,继续修改表的结构来添加外键,代码如下:

create table student(

id int primary key auto_increment,

name char(32) not null,

sex char(32)

);

create table class(

id int primary key auto_increment,

name char(32) not null,

age int,

dept_id int

);

在上述的俩个已经创建好的表中,添加外键:

alter table class add foreign key(dept_id) references student(id)

alter table class:在从表class中进行操作;

add foreign key (dept_id):将从表的字段dept_id添加为外键;

references student(id):映射到主表studentt当中为id的字段

方式一:在创建表的时候增加外键,代码如下create table student(

id int primary key auto_increment,

name char(32) not null,

sex char(32)

);

create table class(

id int primary key auto_increment,

name char(32) not null,

age int,

dept_id int

constraint FK_id foreign key(dept_id) references student(id));格式:[CONSTRAINT symbol] FOREIGN KEY [id] (从表的字段1) REFERENCES tbl_name (主表的字段2)

CONSTRAINT symbol:可以给这个外键约束起一个名字,有了名字,以后找到它就很方便了。如果不加此参数的话,系统会自动分配一个名字。

FOREIGN KEY:将从表中的字段1作为外键的字段。

REFERENCES:映射到主表的字段2。

删除外键:

alter table student drop foreign key 外键名;

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。