哪位高手能给发一些有关MySQL中建立外键约束的详细介绍资料,本人在table中建立外键约束时总是提示同一个错误“ERROR 1005 (HY000): Can't create table 'xxx' (errno: 121)”,不知该如何解决,因此在建table时,不敢加外键约束,在网上收了很久都没找到有关的详解,很是苦恼。
           还请各位高人给予指教!

解决方案 »

  1.   

    你的MYSQL版本是多少?
    用的什么存储引擎?
      

  2.   

    mysql> create table t1 (
        ->  id int primary key,
        ->  col int
        -> )engine=innodb;
    Query OK, 0 rows affected (0.09 sec)mysql> create table t2 (
        ->  id      int primary key,
        ->  tid int,
        ->  FOREIGN KEY (tid) REFERENCES t1(id)
        -> )engine=innodb;
    Query OK, 0 rows affected (0.09 sec)mysql> insert into t2 values (2,1);
    ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint f
    ails (`csdn`.`t2`, CONSTRAINT `t2_ibfk_1` FOREIGN KEY (`tid`) REFERENCES `t1` (`
    id`))
    mysql> insert into t2 values (1,null);
    Query OK, 1 row affected (0.05 sec)mysql> insert into t1 values (1,91);
    Query OK, 1 row affected (0.06 sec)mysql> insert into t2 values (2,1);
    Query OK, 1 row affected (0.03 sec)mysql> select * from t2;
    +----+------+
    | id | tid  |
    +----+------+
    |  1 | NULL |
    |  2 |    1 |
    +----+------+
    2 rows in set (0.00 sec)mysql> select version();
    +----------------------+
    | version()            |
    +----------------------+
    | 5.1.33-community-log |
    +----------------------+
    1 row in set (0.00 sec)mysql>
      

  3.   

    create table t2 (
        ->  id      int primary key,
        ->  tid int,
        ->  FOREIGN KEY (tid) REFERENCES t1(id)
        -> )engine=innodb;
    mysql innodb支持外键约束myisam不支持外键
      

  4.   

    mysql要5.1版本才支持外键约束吧!
    show variables like 'foreign_key_checks' 看看支持不?