How to set up foreign keys when creating a table in MySQL?
In MySQL, you can use the following syntax to set up foreign keys:
CREATE TABLE 表名 (
列名1 数据类型,
列名2 数据类型,
...
FOREIGN KEY (列名1) REFERENCES 参考表名(参考列名),
...
);
In the above syntax, column 1 is the name of the column where the foreign key will be set, reference table name is the name of the table to be referenced, and reference column name is the name of the column to be referenced.
Here is an example:
CREATE TABLE 表1 (
id INT PRIMARY KEY,
name VARCHAR(50)
);
CREATE TABLE 表2 (
id INT PRIMARY KEY,
col1 INT,
col2 VARCHAR(50),
FOREIGN KEY (col1) REFERENCES 表1(id)
);
In the example above, the col1 column in table 2 is set as a foreign key, referencing the id column in table 1.