8

我正在尝试创建一个跨数据库外键。当我在同一个数据库上运行以下代码时

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.t2' (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;

任何帮助将不胜感激。谢谢!

4

1 回答 1

10

你的语法不正确,试试这个

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;
于 2013-03-21T02:31:11.617 回答