How do you add a foreign key constraint in MySQL?

In MySQL, there are two ways to add foreign key constraints: 1. Use the FOREIGN KEY keyword to specify the foreign key constraint when creating a table. For example:

CREATE TABLE 表名 (

  列名 数据类型,

  ...

  FOREIGN KEY (列名) REFERENCES 关联表名(关联列名)

);

2. In an existing table, use the ALTER TABLE statement to add a foreign key constraint. For example:

ALTER TABLE 表名

ADD FOREIGN KEY (列名) REFERENCES 关联表名(关联列名);

Before adding a foreign key constraint, it is important to ensure that the data type and length of the columns being linked and referenced are the same. Additionally, the referenced column must be a primary key or a unique indexed column. If the referenced column is not a primary key or a unique indexed column, a unique index must be created first before adding the foreign key constraint.

bannerAds