create table user(uid int);
create table secuser(id int,sid int);
alter table secuser add constraint fk_sid foreign key (sid) references user(uid);
这样设置外键怎么老是报ERROR 1005 (HY000): Can't create table '.\ptest\#sql-6cc_4.frm' (errno: 150)错误呢

解决方案 »

  1.   

    mysql> alter table user change column uid uid int not null auto_increment primary key;
    Query OK, 0 rows affected (0.06 sec)
    Records: 0  Duplicates: 0  Warnings: 0mysql> alter table secuser add constraint fk_sid foreign key (sid) references user(uid);
    Query OK, 0 rows affected (0.05 sec)
    Records: 0  Duplicates: 0  Warnings: 0
      

  2.   

    问题的根源在于引用的外键字段必须是主键。e.g.
    mysql> create table user(uid int primary key);
    Query OK, 0 rows affected (0.02 sec)mysql> create table secuser(id int,sid int);
    Query OK, 0 rows affected (0.03 sec)mysql> alter table secuser add constraint fk_sid foreign key (sid) references user(uid);
    Query OK, 0 rows affected (0.04 sec)
    Records: 0  Duplicates: 0  Warnings: 0
      

  3.   

    create table user(uid int);1) uid 必须是主键或者唯一键。
    2) user表的存储引擎必须是innodb