跨数据库外键,1215错误

时间:2014-10-25 05:54:44

标签: mysql database foreign-keys

我尝试创建db1表read_x_tag_0列外键db2列是我的代码,不确定我做得对吗?它显示1215错误,找不到原因?

数据库'读' 表'read_x_tag_0'

CREATE TABLE `read_x_tag_0` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `read_id` int(11) unsigned NOT NULL,
  `tag_0_id` int(11) unsigned NOT NULL,
  `tag_0_sequence` int(11) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `read_id` (`read_id`),
  KEY `tag_0_id` (`tag_0_id`),
  CONSTRAINT `read_x_tag_0_ibfk_1` FOREIGN KEY (`read_id`) REFERENCES `read` (`id`) ON DELETE CASCADE,
  CONSTRAINT `read_x_tag_0_ibfk_2` FOREIGN KEY (`tag_0_id`) REFERENCES `tag_0`.`tag_0` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=76 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;



数据库'读' 表'读'

CREATE TABLE `read` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `subject` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `intro` text COLLATE utf8_unicode_ci,
  `content` text COLLATE utf8_unicode_ci,
  `sequence` int(11) unsigned NOT NULL,
  `visible` int(11) unsigned NOT NULL COMMENT '1:visible,0:invisible',
  `create_at` datetime NOT NULL,
  `create_by` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `update_at` datetime NOT NULL,
  `update_by` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

数据库'tag_0'
表'tag_0'

CREATE TABLE `tag_0` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `subject` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `visible` int(11) unsigned NOT NULL COMMENT '1:visible,0:invisible',
  `sequence` int(11) unsigned NOT NULL,
  `create_at` datetime NOT NULL,
  `create_by` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `update_at` datetime NOT NULL,
  `update_by` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),
  UNIQUE KEY `subject` (`subject`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

1 个答案:

答案 0 :(得分:3)

你不应该将.放在反引号内。反引号会转义内部的所有字符,因此不会将其视为数据库和表名之间的分隔符。它应该是:

REFERENCES `db2`.`tag_0`

在您的约束中,您对两个约束使用相同的名称read_x_tag_0。所有约束必须具有不同的名称,因此重命名其中一个。