简体   繁体   English

mysql外键问题

[英]mysql foreign key problem

What is wrong with the foreign key addition here: 这里的外键添加有什么问题:

mysql> create table notes ( 
     id int (11) NOT NULL auto_increment PRIMARY KEY, 
     note_type_id smallint(5) NOT NULL, 
     data TEXT NOT NULL, 
     created_date datetime NOT NULL, 
     modified_date timestamp NOT NULL on update now()) 
     Engine=InnoDB;
Query OK, 0 rows affected (0.08 sec)

mysql> create table notetypes ( 
       id smallint (5) NOT NULL auto_increment PRIMARY KEY, 
       type varchar(255) NOT NULL UNIQUE) 
       Engine=InnoDB;
Query OK, 0 rows affected (0.00 sec)


mysql> alter table `notes` add constraint 
      foreign key(`note_type_id`) references `notetypes`.`id` 
      on update cascade on delete restrict;
ERROR 1005 (HY000): Can't create table './admin/#sql-43e_b762.frm' (errno: 150)  

Thanks 谢谢

JP J.P

I think the FK needs to be named. 我认为FK需要命名。

Try 尝试

ALTER TABLE `test`.`notes` ADD CONSTRAINT `note_type_id` FOREIGN KEY `note_type_id` (`note_type_id`)
    REFERENCES `notetypes` (`id`)
    ON DELETE RESTRICT
    ON UPDATE CASCADE;
mysql> create table notes ( id int (11) NOT NULL auto_increment PRIMARY KEY, note_type_id smallint(5) NOT NULL, data TEXT NOT NULL, created_date datetime NOT NULL, modified_date timestamp NOT NULL on update now()) Engine=InnoDB;
Query OK, 0 rows affected (0.38 sec)

mysql> create table notetypes ( id smallint (5) NOT NULL auto_increment PRIMARY KEY, type varchar(255) NOT NULL UNIQUE) Engine=InnoDB;
Query OK, 0 rows affected (0.74 sec)

mysql> alter table `notes` add constraint foreign key(`note_type_id`) references notetypes (id)  on update cascade on delete restrict;
Query OK, 0 rows affected (0.64 sec)
Records: 0  Duplicates: 0  Warnings: 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM