【问题标题】:How to create a composite Primary Key on a Table [duplicate]如何在表上创建复合主键 [重复]
【发布时间】:2014-07-08 08:59:41
【问题描述】:

我已经创建了一个表,我也插入了一些数据。我在表上有 1 个主键,它按自动生成的数字递增。我有user_idsemester_course_id 列都是foreign_keys。我想在 user_idsemester_course_id 两列上添加复合键。

这样 1 个 Student_id 只能注册 1 个课程。 Semester_Course_idstudent_id 会在表格中重复出现,但它们一起只能出现一次。

请告诉我如何添加复合主键。

谢谢

【问题讨论】:

  • 你需要这个作为 primary 复合键,还是仅仅作为 unique 复合键
  • 我希望它们是独一无二的

标签: php mysql sql primary-key composite-primary-key


【解决方案1】:

在两列的组合上添加unique 约束。

alter table table_name
  add constraint uk_sid_coursid
      unique key ( studentid, semistercourseid )

要使此复合键用作辅助主键,请将此字段中的每个定义为not null

【讨论】:

    【解决方案2】:

    试试这个

    ALTER TABLE TABLE_NAME ADD unique index(StudentId,SemisterCourseId);
    

    【讨论】:

    • 一张表只能有一个primary key。 OP 说表有'1 primary key on the table which is incremented by auto-generated number'。所以这是行不通的。
    • 好的。很好,你改变了你的解决方案。
    猜你喜欢
    • 2014-06-13
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多