Home > Database > Mysql Tutorial > How Do I Reference a Multi-Column Primary Key in MySQL?

How Do I Reference a Multi-Column Primary Key in MySQL?

DDD
Release: 2024-12-02 18:16:15
Original
680 people have browsed it

How Do I Reference a Multi-Column Primary Key in MySQL?

Referencing a Multi-Column Primary Key in MySQL

When establishing relationships between tables, it's common to encounter scenarios where a primary key comprises multiple columns. In MySQL, creating a foreign key to such a table requires a tailored approach.

Consider a scenario where you have a table with the following primary key:

CREATE TABLE ProductAttributes (
  product_id INT NOT NULL,
  attribute_id INT NOT NULL,
  PRIMARY KEY (product_id, attribute_id)
);
Copy after login

Now, suppose you have another table that needs to reference the ProductAttributes table. To establish a foreign key that links the two tables, follow these steps:

CREATE TABLE MyReferencingTable AS (
  [COLUMN DEFINITIONS]
  refcol1 INT NOT NULL,
  rofcol2 INT NOT NULL,
  CONSTRAINT fk_mrt_ot FOREIGN KEY (refcol1, refcol2)
                        REFERENCES ProductAttributes(product_id, attribute_id)
) ENGINE=InnoDB;
Copy after login

By specifying the columns in the referencing table and the corresponding columns in the primary key table, you create a foreign key constraint. This constraint ensures that each row in the referencing table has a matching primary key in the primary key table.

Considerations:

  • MySQL requires foreign keys to be indexed, which explains the index on the referencing columns.
  • Utilize the constraint syntax to name the constraint for easier alteration or deletion later on.
  • Remember that InnoDB enforces foreign keys, while MyISAM ignores them.

The above is the detailed content of How Do I Reference a Multi-Column Primary Key in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template