我正在尝试创建一个跨数据库外键。当我在同一个数据库
上运行以下代码时CREATE TABLE `t1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`int_id` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `int_id` (`int_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `t2` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ext_id` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `ext_id` (`ext_id`),
CONSTRAINT `t2_ibfk_1` FOREIGN KEY (`ext_id`) REFERENCES `t1` (`int_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
然而,当在一个数据库(d1)上创建t1,然后在第二个数据库(d2)上运行以下代码时,我收到了通用错误:#1005 - Can't create table 'userdata。2' (errno: 150)
CREATE TABLE `t2` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ext_id` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `ext_id` (`ext_id`),
CONSTRAINT `t2_ibfk_1` FOREIGN KEY (`ext_id`) REFERENCES `d1.t1` (`int_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
任何帮助将不胜感激。谢谢!
你的语法不正确,试试这个
CREATE TABLE `t2` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ext_id` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `ext_id` (`ext_id`),
CONSTRAINT `t2_ibfk_1` FOREIGN KEY (`ext_id`) REFERENCES `d1`.`t1` (`int_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;