Home >Database >Mysql Tutorial >How to Define Foreign Keys Referencing Multi-Column Primary Keys in MySQL?
Understanding Foreign Keys for Multi-Column Primary Keys in MySQL
When creating relationships between tables in a relational database, it's essential to understand how to establish foreign keys. In MySQL, a common scenario involves linking a table to another table with a multi-column primary key.
Consider a table named ProductAttribute that has two primary key columns: product_id and attribute_id. You want to create another table, ProductDetails, that references the ProductAttribute table.
To establish a foreign key in ProductDetails that links to the ProductAttribute table, you can use the following syntax:
CREATE TABLE ProductDetails ( [COLUMN DEFINITIONS] product_id INT NOT NULL, attribute_id INT NOT NULL, CONSTRAINT fk_product_details_product_attribute FOREIGN KEY (product_id, attribute_id) REFERENCES ProductAttribute(product_id, attribute_id) ) ENGINE=InnoDB;
Important Considerations:
The above is the detailed content of How to Define Foreign Keys Referencing Multi-Column Primary Keys in MySQL?. For more information, please follow other related articles on the PHP Chinese website!