我在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_id
和restriction_id
对?
INSERT INTO
restrictions_projects
(project_id
,restriction_id
) 价值观(1,2)// ??? ON DUPLICATE KEY UPDATEproject_id
= 1 ANDrestriction_id
= 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);
您也可以使用唯一索引执行此操作,这实际上是相同的。