MySQL:引用外键

时间:2013-02-10 07:37:21

标签: mysql foreign-keys

我试图在mysql中引用一个外键到它的父键,我得到一个尴尬的错误。

我尝试了以下内容。

ALTER TABLE `website`
  ADD CONSTRAINT `website_cms_fk1` FOREIGN KEY (`cms_id`) REFERENCES `cms_technology` (`ID`);

ALTER TABLE website ADD FOREIGN KEY (cms_id) REFERENCES cms_technology (ID)

我收到以下错误。

*#1005 - 无法创建表'脚本。#sql-5203_110b8ba'(错误号:150)*

以下是我的表格

CREATE TABLE IF NOT EXISTS `cms_technology` (
  `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `cms_name` varchar(250) NOT NULL DEFAULT '',
  `cms_description` varchar(250) NOT NULL DEFAULT '',
  PRIMARY KEY (`ID`)
);

INSERT INTO `cms_technology` (`ID`, `cms_name`, `cms_description`) VALUES
(1, 'Wordpress', 'WordPress › Blog Tool, Publishing Platform, and CMS');

CREATE TABLE IF NOT EXISTS `website` (
  `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `website_url` varchar(60) NOT NULL DEFAULT '',
  `website_ip` varchar(20) NOT NULL DEFAULT '',
  `website_title` varchar(250) NOT NULL DEFAULT '',
  `website_status` varchar(10) NOT NULL DEFAULT '',
  `website_scanned` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `website_response` int(3) NOT NULL DEFAULT '0',
  `cms_id` int(5)  NOT NULL DEFAULT '0',
  PRIMARY KEY (`ID`)
);

INSERT INTO `website` (`ID`, `website_url`, `website_ip`, `website_title`, `website_status`, `website_scanned`, `website_response`, `website_cms`) VALUES
(1, 'http://www.wpbeginner.com/', '', '', '', '0000-00-00 00:00:00', 0, 0);

我做错了什么?

2 个答案:

答案 0 :(得分:2)

您需要更改表cms_ID中列website的数据类型才能引用表cms_technology。 to列的属性必须相同。

CREATE TABLE IF NOT EXISTS `website` (
  `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `website_url` varchar(60) NOT NULL DEFAULT '',
  `website_ip` varchar(20) NOT NULL DEFAULT '',
  `website_title` varchar(250) NOT NULL DEFAULT '',
  `website_status` varchar(10) NOT NULL DEFAULT '',
  `website_scanned` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `website_response` int(3) NOT NULL DEFAULT '0',
  `cms_id` bigint(20) unsigned NOT NULL,                        -- <<== HERE
  PRIMARY KEY (`ID`)
);

答案 1 :(得分:0)

我错过了 KEY cms_idcms_id

 CREATE TABLE IF NOT EXISTS `website` (
      `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
      `website_url` varchar(60) NOT NULL DEFAULT '',
      `website_ip` varchar(20) NOT NULL DEFAULT '',
      `website_title` varchar(250) NOT NULL DEFAULT '',
      `website_status` varchar(10) NOT NULL DEFAULT '',
      `website_scanned` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
      `website_response` int(3) NOT NULL DEFAULT '0',
      `cms_id` bigint(20) unsigned NOT NULL DEFAULT '0',
      PRIMARY KEY (`ID`),
      KEY `cms_id` (`cms_id`)
    );

ALTER TABLE `website`
  ADD CONSTRAINT `website_cms_fk1` FOREIGN KEY (`cms_id`) REFERENCES `cms_technology` (`ID`);