mysql外键注意什么_MySQL 外键 注意

今天偶然间发现一个小细节

关于建立表的外键:

建立MySQL外键时出现一个error:

1005 - Can't create table 'dot_1.#sql-218_11' (errno: 150)

查询后才发现MySQL在建立表的外键的时候有一个要求:

建立外键的列必须有索引!

举例:

tclass(id,cname);

tstudent(id,sname,sclass);

要求学生的sclass字段建立外键到tclass的id,有了下面这一步才得以正确执行,否则报error:

create index idx_clazz on tstudent(sclass);

--------------------------------------------溜须拍马的分割线-------------------------------------

但是Oracle不需要建立index,直接可以建立索引,不会报错,执行通过;

希望各位遇到类似问题的码友注意了。

---------------------------------------------穿越2000年的分割线-------------------------------

Mysql数据库要创建FK外键,必须要INNODB的engine,否则扯淡!

create table clazz(

id int primary key auto_increment not null ,

name varchar(20)

)engine=innodb;

create table student(

id int primary key auto_increment not null,

sname varchar(20),

clazzid int,

key student_class_id (clazzid),

constraint fk_student_clazz foreign key (clazzid) references clazz (id)

)engine=innodb;

执行查询结果:

show create table student;

| student | CREATE TABLE `student` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`sname` varchar(20) DEFAULT NULL,

`clazzid` int(11) DEFAULT NULL,

PRIMARY KEY (`id`),

KEY `student_class_id` (`clazzid`),

CONSTRAINT `fk_student_clazz` FOREIGN KEY (`clazzid`) REFERENCES `clazz` (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1 |

"CONSTRAINT `fk_student_clazz` FOREIGN KEY "

更换之后:

drop table student,clazz;

create table clazz(

id int primary key auto_increment not null ,

name varchar(20)

);

create table student(

id int primary key auto_increment not null,

sname varchar(20),

clazzid int,

key student_class_id (clazzid),

constraint fk_student_clazz foreign key (clazzid) references clazz (id)

);

show create table student;

//-----------------------------结果:--------------

| student | CREATE TABLE `student` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`sname` varchar(20) DEFAULT NULL,

`clazzid` int(11) DEFAULT NULL,

PRIMARY KEY (`id`),

KEY `student_class_id` (`clazzid`)

) ENGINE=MyISAM DEFAULT CHARSET=latin1 |

默认是MyISAM;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值