乐闻世界logo
搜索文章和话题

What is a composite primary key in MySQL?

1个答案

1

Composite Key refers to a primary key composed of two or more columns, where the combination uniquely identifies each row in the table. Its purpose is to achieve record uniqueness when a single column cannot uniquely identify a record.

Example Explanation

Assume we have a school's database with a table called Enrollment Records. This table records students' course selections, and its structure may include the following fields:

  • Student ID: Represents the unique identifier for a student.
  • Course ID: Represents the unique identifier for a course.
  • Enrollment Time: The time when the student enrolled.
  • Grade: The grade the student received for the course.

In this example, neither the Student ID nor the Course ID alone can uniquely identify a record in the table, as a student may enroll in multiple courses, and a course may be selected by multiple students. At this point, we can combine the Student ID and Course ID columns to serve as the composite key for this table. This way, any record can be uniquely identified by the combination of these two columns.

Usage Scenarios

In practical applications, composite keys are typically used for:

  1. Join Tables: When implementing many-to-many relationships, join tables often use two foreign keys as a composite key to ensure the uniqueness of the relationship.
  2. Business Requirements: When business rules require that records in the table must be uniquely defined by multiple fields combined.

Composite keys not only help databases enforce data uniqueness but also improve query efficiency, as database systems automatically create indexes for primary keys. However, using composite keys has drawbacks, such as making indexes more complex and consuming more storage space. Therefore, when designing databases, it is necessary to weigh the pros and cons based on actual application scenarios.

2024年10月26日 22:29 回复

你的答案