在两个唯一的列上创建主键

时间:2018-04-27 04:28:29

标签: mysql

如果这个问题是一个愚蠢的问题,请道歉。我试图避免创建任意索引列作为主键。我想做的是以下几点:

根据student_id + section_id列的唯一性创建主键(表中没有单独的唯一性,但两者一起将是唯一的)。以下不起作用,但我想知道是否会有类似的东西?

CREATE TABLE Registration 
    (
        student_id VARCHAR(10) NOT NULL,
        section_id VARCHAR (6) NOT NULL,
        midterm_grade VARCHAR(2), 
        final_grade VARCHAR(2),

        CONSTRAINT Registration_unique UNIQUE (student_id, section_id),
        CONSTRAINT Registration_pk PRIMARY KEY (Registration_unique),

        CONSTRAINT Registration_fk1 FOREIGN KEY (student_id) REFERENCES Student(student_id)
            ON DELETE CASCADE,
        CONSTRAINT Registration_fk2 FOREIGN KEY (section_id) REFERENCES Section(section_id)
            ON DELETE CASCADE
    )
    ENGINE = INNODB;

1 个答案:

答案 0 :(得分:1)

您不需要image = request.FILES['image'] ,因为您可以制作合成UNIQUE

PRIMARY KEY (student_id, section_id)

如果您希望CREATE TABLE Registration ( student_id VARCHAR(10) NOT NULL, section_id VARCHAR (6) NOT NULL, midterm_grade VARCHAR(2), final_grade VARCHAR(2), CONSTRAINT Registration_pk PRIMARY KEY (student_id, section_id), CONSTRAINT Registration_fk1 FOREIGN KEY (student_id) REFERENCES Student(student_id) ON DELETE CASCADE, CONSTRAINT Registration_fk2 FOREIGN KEY (section_id) REFERENCES Section(section_id) ON DELETE CASCADE ) 是唯一的,而student_id将是唯一的,您需要制作两个唯一的密钥

section_id

这意味着您只能插入CREATE TABLE Registration ( student_id VARCHAR(10) NOT NULL, section_id VARCHAR (6) NOT NULL, midterm_grade VARCHAR(2), final_grade VARCHAR(2), CONSTRAINT Registration_unique_student_id UNIQUE (student_id), CONSTRAINT Registration_unique_section_id UNIQUE (section_id), CONSTRAINT Registration_pk PRIMARY KEY (student_id, section_id), CONSTRAINT Registration_fk1 FOREIGN KEY (student_id) REFERENCES Student(student_id) ON DELETE CASCADE, CONSTRAINT Registration_fk2 FOREIGN KEY (section_id) REFERENCES Section(section_id) ON DELETE CASCADE ) One student - One section类型的行。

如果您想为多名学生使用相同的部分,请删除第二个唯一One section - One student