MYSQL-无法创建外部密钥

时间:2019-09-01 14:56:29

标签: mysql

我是一个自学成才的CS,实际上是mySQL的新手。我创建了一个名为“ jobs”的表。我想创建一个包含3列的新表keywords

  • keyword_id作为主键
  • job_id作为jobs表中的外键
  • keyword,文本

这是我写的查询:

   CREATE TABLE `keywords` (
  `keyword_id` int(11) NOT NULL AUTO_INCREMENT,
   PRIMARY KEY(`keyword_id`),
  `keyword` text NOT NULL,
  FOREIGN KEY (job_id) REFERENCES jobs(job_id)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=latin1;

我收到此错误消息:

Key column 'job_id' doesn't exist in table

当前作业表代码如下:

    CREATE TABLE `jobs` (
      `title` text NOT NULL,
      `type` text NOT NULL,
      `location` text NOT NULL,
      `salary` int(11) NOT NULL,
      `description` text NOT NULL,
      `date` date NOT NULL,
      `job_id` int(11) NOT NULL AUTO_INCREMENT,
      PRIMARY KEY (`job_id`)

) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=latin1;

1 个答案:

答案 0 :(得分:2)

您需要在keywords表中有一列来保存外键。

CREATE TABLE `jobs` (
      `title` text NOT NULL,
      `type` text NOT NULL,
      `location` text NOT NULL,
      `salary` int(11) NOT NULL,
      `description` text NOT NULL,
      `date` date NOT NULL,
      `job_id` int(11) NOT NULL AUTO_INCREMENT,
      PRIMARY KEY (`job_id`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=latin1;

CREATE TABLE `keywords` (
    `keyword_id` int(11) NOT NULL AUTO_INCREMENT,
    `keyword` text NOT NULL,
    `job_id` int(11) NOT NULL,              #<- new column
    PRIMARY KEY(`keyword_id`),
    FOREIGN KEY (job_id) REFERENCES jobs(job_id)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=latin1;