我在MySQL InnoDB中创建了一个像这样的表:
CREATE TABLE `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,`type` enum('MANUAL','FACEBOOK') NOT NULL DEFAULT 'MANUAL',`role` enum('COOK','HOST','ALL') NOT NULL DEFAULT 'ALL',`about_me` varchar(1000) DEFAULT NULL,`food_preferences` varchar(1000) DEFAULT NULL,`cooking_experience` varchar(1000) DEFAULT NULL,`with_friend` bit(1) DEFAULT b'0',PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
接下来我尝试添加一个带有这样一个语句的表(在创建表时没有添加外键,因为它有问题):
CREATE TABLE `messages` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,`from` bigint(20) NOT NULL,`to` bigint(20) NOT NULL,`content` varchar(10000) NOT NULL,`timestamp_sent` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,`timestamp_read` timestamp NULL DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
创建表后,我需要最终在引用’users’的’from’和’to’字段中添加外键.’id’字段:
ALTER TABLE `messages`
ADD CONSTRAINT `messages_users_fk`
FOREIGN KEY (`from`,`to` )
REFERENCES `users` (`id`,`id` )
ON DELETE SET NULL
ON UPDATE CASCADE,ADD INDEX `messages_users_fk_idx` (`from` ASC,`to` ASC)
我得到的错误是:
ERROR: Error 1822: Failed to add the foreign key constraint. Missing index for constraint ‘messages_users_fk’ in the referenced table ‘users’.
但’用户’表在’id’上有一个PRIMARY索引…
还试图做一个较小的步骤,并为’from’字段添加外键:
ALTER TABLE `messages`
ADD CONSTRAINT `messages_users_fk`
FOREIGN KEY (`from` )
REFERENCES `users` (`id` )
ON DELETE SET NULL
ON UPDATE CASCADE,ADD INDEX `messages_users_fk_idx` (`from` ASC) ;
错误略有不同:
ERROR: Error 1825: Failed to add the foreign key constraint on table ‘messages’. Incorrect options in FOREIGN KEY constraint ‘cook4food/messages_users_fk’.
字段的类型是相同的(bigint(20)NOT NULL),因为它被建议作为其他StackOverflow线程中的问题的原因.我的表没有被分区(MysqL手册指出这是在InnoDB中具有外键约束的限制). ‘messages’表当前不存储任何行,因此存储的数据不会以任何方式出现问题.我被卡住了,请帮忙.
最佳答案
如果您具有相应的权限,则可以发出以下查询:
SHOW ENGINE innodb STATUS
…它会告诉你(在其他一些信息中)错误的确切细节:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
130311 13:30:06 Error in foreign key constraint of table test/#sql-71c_6:
FOREIGN KEY (`from`,`to` ASC):
You have defined a SET NULL condition though some of the
columns are defined as NOT NULL.
在父记录删除时,您不能使子记录为NULL,因为列是非NULL:
`from` bigint(20) NOT NULL,
编辑:此外,我无法看到单个复合键的目的.我想你想要两个单键.