如何限制在表中插入重复的值对?

时间:2018-02-04 16:20:54

标签: mysql sql

我在MySQL DB(MariaDB)中有以下表格:

CREATE TABLE `restrictions_projects` (
  `ID` int(11) NOT NULL,
  `project_id` int(11) NOT NULL,
  `restriction_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `restrictions_projects`
  ADD PRIMARY KEY (`ID`),
  ADD KEY `project_id` (`project_id`),
  ADD KEY `restriction_id` (`restriction_id`);

ALTER TABLE `restrictions_projects`
  MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT;

ALTER TABLE `restrictions_projects`
  ADD CONSTRAINT `restrictions_prfk_1` FOREIGN KEY (`project_id`) REFERENCES `projects` (`ID`),
  ADD CONSTRAINT `restrictions_prfk_2` FOREIGN KEY (`restriction_id`) REFERENCES `restrictions` (`ID`);
COMMIT;

如何限制插入重复的project_idrestriction_id对?

  

INSERT INTO restrictions_projectsproject_idrestriction_id)   价值观(1,2)// ??? ON DUPLICATE KEY UPDATE project_id = 1 AND   restriction_id = 2

2 个答案:

答案 0 :(得分:1)

您需要在两列

上使用复合唯一键
UNIQUE (project_id,restriction_id)

您应该更改表格以添加唯一键

ALTER TABLE restrictions_projects ADD CONSTRAINT restrictions_projects_uniq UNIQUE (project_id,restriction_id)

答案 1 :(得分:1)

添加唯一约束:

ALTER TABLE restrictions_projects
  ADD CONSTRAINT unq_restrictions_2 UNIQUE(project_id, restriction_id);

您也可以使用唯一索引执行此操作,这实际上是相同的。