我正在尝试创建两个表之间的关系。这里是每个表的查询和外键创建,
CREATE TABLE IF NOT EXISTS `quotes` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`quote` text COLLATE utf8_unicode_ci NOT NULL,
`author` int(11) NOT NULL,
`topic` int(11) NOT NULL,
`language` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`),
KEY `author` (`author`),
KEY `topic` (`topic`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE IF NOT EXISTS `authors` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`author` int(11) NOT NULL,
`period` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`photo` text COLLATE utf8_unicode_ci NOT NULL,
`references` text COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`),
KEY `author` (`author`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
ALTER TABLE `quotes` ADD FOREIGN KEY ( `author` ) REFERENCES `mytestdb`.`authors` (
`id`
) ON DELETE RESTRICT ON UPDATE RESTRICT ;
但它抛出了以下错误,
Error creating foreign key on author (check data types)
我不知道这个错误是怎么回事。如有任何帮助,我们将不胜感激。
数据类型和符号必须是相同的
int
与unsigned int
不同
显示宽度与无关
author
是一个有符号的int
id
是无符号int
从手册页面:
外键和引用键中的相应列必须具有相似的数据类型。整数类型的大小和符号必须为同样。字符串类型的长度不必相同。对于非二进制(字符)字符串列、字符集和排序规则必须相同。
它们的大小(int)相同。他们不是同一个符号。
10和11的显示宽度无关紧要。
Demo
create table referenced
( id int(11) primary key
);
create table referencing
( id int primary key,
author int(10) not null,
CONSTRAINT fk_blah FOREIGN KEY (author) REFERENCES referenced(id)
);
工作没有问题
CREATE TABLE IF NOT EXISTS `quotes` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`quote` text COLLATE utf8_unicode_ci NOT NULL,
`author` int(11) NOT NULL,
`topic` int(11) NOT NULL,
`language` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`),
KEY `author` (`author`),
KEY `topic` (`topic`)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `authors` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`author` int(11) NOT NULL,
`period` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`photo` text COLLATE utf8_unicode_ci NOT NULL,
`references` text COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`),
KEY `author` (`author`),
CONSTRAINT fk_blah222 FOREIGN KEY (author) REFERENCES quotes(id)
) ENGINE=InnoDB;
工作没有问题
为了完整性。
我发现添加外键作为对现有表的更改也会产生此错误。
使用PHPMyAdmin,我必须删除该表,然后用外键重新创建它。创建表之后,我必须使用PHPMyAdmin中的表"relationship-view"添加外键约束。
这并不能说明错误最初发生的原因,但这确实解决了问题。
祝你好运。