MySQL中的多列外键?

2021-11-20 00:00:00 mysql

我有一个表,其主键由两列(product_id、attribute_id)组成.我有另一个表需要引用这个表.如何在另一个表中创建外键以将其链接到具有两个主键的表中的行?

I have a table that has a primary key consisting of two columns (product_id, attribute_id). I have another table that needs to reference this table. How can I make a foreign key in the other table to link it to a row in the table with two primary keys?

推荐答案

应该这样做:

CREATE TABLE MyReferencingTable AS (
   [COLUMN DEFINITIONS]
   refcol1 INT NOT NULL,
   rofcol2 INT NOT NULL,
   CONSTRAINT fk_mrt_ot FOREIGN KEY (refcol1, refcol2)
                        REFERENCES OtherTable(col1, col2)
) ENGINE=InnoDB;

  • MySQL 需要索引外键,因此需要索引引用列
  • 使用约束语法,您可以命名约束,以便在需要时更轻松地更改和删除.
  • InnoDB 强制执行外键,而 MyISAM 没有.(语法被解析但被忽略)

相关文章