mysql 是 5.1版本的 ,表的类型是InnoDB 

解决方案 »

  1.   

    试了下,你上面的错误的确是由于你建立外键时所要关联的另外一个表的对应字段不是主键引起的,测试如下:
    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: 0mysql> 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>可以看到,外键已经成功建立
      

  2.   

    show create table 表名把两个表的 create table 语句贴出来看一下。如楼上所说。1. 被参照表听对应字段上是否创建的索引?
    2. 两表的这个字段类型是否相同?
      

  3.   

    感谢大家提示 解决了  虽然类型都int类型的 问题就是两表字段属性不一样 一个是unsigned选项勾上了一个没勾
      

  4.   

    恩,这个就是类型不一致引起的啦
    建立外键是mysql下常见这样的错误。