请教下MYSQL的外键的问题。

2013-09-23 05:08:19
create table studcourse
(stucourseid int primary key auto_increment,
sid int references student(sid),
cid int references course(cid),
grade int(3) not null

);

这样子创建,设置了外键么。这是奥忍考的,可是我电脑上只有MYSQL,本来这么写也没问题。

结果我SHOW create table studcourse的时候,没有看到外键的信息。
studcourse | CREATE TABLE `studcourse`
`stucourseid` int(11) NOT NULL AUTO_IN
`sid` int(11) DEFAULT NULL,
`cid` int(11) DEFAULT NULL,
`grade` int(3) NOT NULL,
PRIMARY KEY (`stucourseid`)
ENGINE=InnoDB DEFAULT CHARSET=utf8 |

但是接着,我想添加外键。
alter table studcourse add foreign key(sid) references student(cid);

结果提示错误

Can't create table 'hibernate.#sql-7c8_1' (errno: 150)


...全文
93 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
steely_chen 2013-09-23
  • 打赏
  • 举报
回复
引用 2 楼 yousteely 的回复:
估计你使用的是MyISAM 数据引擎,所以不支持外键,你可以将数据库引擎改为innodb试一下应该就可以了。 以你的代码为例

reate table studcourse(
 stucourseid int primary key auto_increment,
 sid int references student(sid),
 cid int references course(cid),
 grade int(3) not null,
 CONSTRAINT FOREIGN KEY (`sid`) references `student`(`sid`),
 CONSTRAINT FOREIGN KEY (`cid`) references `course`(`cid`)
 )engine=innoDB;
执行这上面的sql之前要保证student 和course这两个表也是innoDB才行,至于怎么修改数据库引擎可以在网上找。 create table t5 (c1 int ,c2 int, CONSTRAINT FOREIGN key (`c2`) references `t3`(`c1`))engine=innoDB
后面是我测试的代码,忘了删,不好意思。
steely_chen 2013-09-23
  • 打赏
  • 举报
回复
估计你使用的是MyISAM 数据引擎,所以不支持外键,你可以将数据库引擎改为innodb试一下应该就可以了。 以你的代码为例

reate table studcourse(
 stucourseid int primary key auto_increment,
 sid int references student(sid),
 cid int references course(cid),
 grade int(3) not null,
 CONSTRAINT FOREIGN KEY (`sid`) references `student`(`sid`),
 CONSTRAINT FOREIGN KEY (`cid`) references `course`(`cid`)
 )engine=innoDB;
执行这上面的sql之前要保证student 和course这两个表也是innoDB才行,至于怎么修改数据库引擎可以在网上找。 create table t5 (c1 int ,c2 int, CONSTRAINT FOREIGN key (`c2`) references `t3`(`c1`))engine=innoDB
  • 打赏
  • 举报
回复
程序里很少用外键了

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧