两个表类型都是InnoDB
要关联的两个字段都是int类型
两个表都是空表创建关联时报错误号1005
错误信息:
Can't create table '.\study\#sql-15ac_1.frm' (errno: 150)请问如何解决

解决方案 »

  1.   

    数据库的名字叫study
    CREATE TABLE `codedb` (
      `id` int(11) NOT NULL auto_increment,
      `code` int(11) NOT NULL,
      `text` varchar(50) default NULL,
      `type` varchar(15) default NULL,
      `flag` char(1) NOT NULL default 'T',
      PRIMARY KEY  (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=gbk;
    CREATE TABLE `userdb` (
      `id` int(11) NOT NULL auto_increment,
      `username` varchar(50) NOT NULL,
      `password` varchar(50) NOT NULL,
      `sex` int(11) NOT NULL,
      `authenticname` varchar(50) NOT NULL,
      `flag` char(1) NOT NULL default 'T',
      PRIMARY KEY  (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=gbk;
    alter table `study`.`userdb` add constraint `FK_userdb` FOREIGN KEY (`sex`) REFERENCES `codedb` (`code`)
      

  2.   

    你的`codedb`  `code`  上没有索引啊。被外键参照的必须是索引。mysql> alter table codedb add INDEX (code) ;
    Query OK, 0 rows affected (0.14 sec)
    Records: 0  Duplicates: 0  Warnings: 0mysql> alter table `userdb` add constraint `FK_userdb` FOREIGN KEY (`sex`) REFER
    ENCES `codedb` (`code`);
    Query OK, 0 rows affected (0.13 sec)
    Records: 0  Duplicates: 0  Warnings: 0mysql>