我有两列。 SQL是:
CREATE TABLE tdegree
(
degree varchar(25) NOT NULL primary key
)
CREATE TABLE tstudy
(
study varchar(25) NOT NULL unique,
degree varchar(25) NOT NULL FOREIGN KEY REFERENCES tdegree (degree)
)
如下图所示我想添加记录
掌握它
mphil it
但不是
掌握它
掌握它
如果我在学习领域应用了唯一约束,那么它就不允许我添加
掌握它
mphil it
我必须应用哪些限制?
答案 0 :(得分:0)
如果我理解正确,您希望study
和degree
的组合是唯一的,但值可以在各个列中重复,例如第1行是Master + IT,第2行是MPhil + IT,因此两行都是唯一的,但study
列具有重复值IT。在这种情况下,您需要在两个列上添加唯一约束,如下所示:
alter table tstudy add constraint cunique unique(study,degree)
请注意,您还需要更改tstudy
表的定义并删除study
列上的唯一约束,否则即使添加了上述约束,您也会遇到唯一的约束违规错误:
CREATE TABLE tstudy
(
study varchar(25) NOT NULL,
degree varchar(25) NOT NULL FOREIGN KEY REFERENCES tdegree (degree)
)