MySQL与2表的关系

时间:2019-01-09 09:27:07

标签: mysql foreign-keys relational-database

我有两个表:

CREATE TABLE `companies` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`industry_id` int(11) DEFAULT NULL,
 ... other fields ...
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE 
 CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`) 
 ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

和:

CREATE TABLE `industries` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

我试图向第二张表添加外键:

ALTER TABLE industries ADD FOREIGN KEY (id) REFERENCES companies(industry_id) ON DELETE RESTRICT;

但是我遇到下一个错误:

  

无法添加外键约束

如何添加正确的fkey?

1 个答案:

答案 0 :(得分:1)

我想你做错了。主键不能为外键。 让我们进行一些更改,可以为您带来相同的价值

ALTER TABLE companies ADD FOREIGN KEY (industry_id) REFERENCES industries(id) ON DELETE RESTRICT;