"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Implement Composite Foreign Keys in MySQL?

How to Implement Composite Foreign Keys in MySQL?

Published on 2024-12-26
Browse:629

How to Implement Composite Foreign Keys in MySQL?

Implementing Composite Foreign Keys in SQL

One common database design involves establishing relationships between tables using composite keys. A composite key is a combination of multiple columns that uniquely identifies a record in a table. In this scenario, you have two tables, tutorial and group, where you need to link the composite unique key in tutorial to a field in group.

According to MySQL documentation, MySQL supports foreign key mapping to composite keys. However, to establish this relationship, you will need to create multiple columns in the referencing table (group) to match the primary key columns in the referenced table (tutorial).

Here are the steps on how to create the foreign key mapping:

-- Alter the 'group' table to add the composite foreign key columns
ALTER TABLE `group`
ADD COLUMN `beggingTime` time NOT NULL,
ADD COLUMN `day` varchar(8) NOT NULL,
ADD COLUMN `tutorId` int(3) NOT NULL;

-- Add the foreign key constraint
ALTER TABLE `group`
ADD FOREIGN KEY (`beggingTime`, `day`, `tutorId`)
REFERENCES `tutorial`(`beggingTime`, `day`, `tutorId`);

By creating the three foreign key columns (beggingTime, day, and tutorId) in the group table, you establish the relationship with the composite primary key in the tutorial table. This allows you to join and retrieve data from both tables based on the composite key.

It's important to note that while using composite foreign keys is technically supported, it's generally recommended to use a single-column primary key instead. This is because composite keys can impact performance and increase the complexity of your database design. If possible, consider re-architecting your tables to utilize a single-column primary key in tutorial.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3