57,065
社区成员
发帖
与我相关
我的任务
分享试了下,你上面的错误的确是由于你建立外键时所要关联的另外一个表的对应字段不是主键引起的,测试如下:
mysql> create table t1(id int, memo varchar(20));
Query OK, 0 rows affected (0.00 sec)
mysql> create table t2(itemid int, name varchar(20));
Query OK, 0 rows affected (0.01 sec)
下面用语句在上面的表t2的列itemid上关联表t1的列id建立外键:
mysql> alter table t2 add constraint foreign key(itemid) references t1(id);
ERROR 1005 (HY000): Can't create table '.\shen\#sql-664_4.frm' (errno: 150)
看到没有,这个错误跟你操作提示的错误一致的,下面进行解决:
mysql> show create table t1\G
*************************** 1. row ***************************
Table: t1
Create Table: CREATE TABLE `t1` (
`id` int(11) NOT NULL default '0',
`memo` varchar(20) default NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
mysql> show create table t2\G
*************************** 1. row ***************************
Table: t2
Create Table: CREATE TABLE `t2` (
`itemid` int(11) default NULL,
`name` varchar(20) default NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
在表t1的对应列id建立主键(primary key):
mysql> alter table t1 add constraint primary key(id);
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0
在表t1的对应列id建立主键(primary key)
mysql> show create table t1\G
*************************** 1. row ***************************
Table: t1
Create Table: CREATE TABLE `t1` (
`id` int(11) NOT NULL,
`memo` varchar(20) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
在表t2的列item关联表t1的列id建立外键(foreign key):
mysql> alter table t2 add constraint foreign key(itemid) references t1(id);
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> show create table t2\G
*************************** 1. row ***************************
Table: t2
Create Table: CREATE TABLE `t2` (
`itemid` int(11) default NULL,
`name` varchar(20) default NULL,
KEY `itemid` (`itemid`),
CONSTRAINT `t2_ibfk_1` FOREIGN KEY (`itemid`) REFERENCES `t1` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
mysql>
可以看到,外键已经成功建立