我有两个表books
和borrowing requests
-我正在做一个学习MySQL的研究项目。尝试使用FK链接这两个表,并不断出现错误:
"SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")
除了文档之外,我实际上搜索了SO上的所有相关主题,但是都没有成功。类型是相同的,列都是无符号的,一个主键,等等。据我所知,我尊重所有规定。但这行不通!我想念什么?
这是两个表和fk加法查询:
CREATE TABLE `books` (
`book_id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`book_title` VARCHAR(100) NOT NULL,
`author_id` INT(11) NOT NULL,
`book_condition` INT(5) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=23453 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
CREATE TABLE `borrowing_requests` (
`request_id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`user_id` INT(11) NOT NULL,
`book_id` INT(11) UNSIGNED NOT NULL,
`due_date` VARCHAR(55) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=23453 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
FK查询:
ALTER TABLE `books` ADD CONSTRAINT books_fk FOREIGN KEY (`book_id`)
REFERENCES `borrowing_requests`(`book_id`)
ON DELETE NO ACTION ON UPDATE NO ACTION
答案 0 :(得分:2)
您有外键“向后”-借阅请求应引用一本书,而不是相反:
ALTER TABLE `borrowing_requests` ADD CONSTRAINT books_fk FOREIGN KEY (`book_id`)
REFERENCES `books`(`book_id`)
ON DELETE NO ACTION ON UPDATE NO ACTION