We can set foreign key constraints when creating the table.
In the CREATE TABLE statement, specify the foreign key through the FOREIGN KEY keyword. The specific syntax format is as follows:
[CONSTRAINT <外键名>] FOREIGN KEY 字段名 [,字段名2,…] REFERENCES <主表名> 主键列1 [,主键列2,…]
Example:
Now create a foreign key in the test_db database Department table tb_dept1, the table structure is as shown in the figure below:
The SQL statement and running results to create tb_dept1 are as follows.
mysql> CREATE TABLE tb_dept1 -> ( -> id INT(11) PRIMARY KEY, -> name VARCHAR(22) NOT NULL, -> location VARCHAR(50) -> ); Query OK, 0 rows affected (0.37 sec)
Create the data table tb_emp6, and create a foreign key constraint on the table tb_emp6, so that its key deptId is associated with the primary key id of the table tb_dept1 as a foreign key. The SQL statement and running results are as follows.
mysql> CREATE TABLE tb_emp6 -> ( -> id INT(11) PRIMARY KEY, -> name VARCHAR(25), -> deptId INT(11), -> salary FLOAT, -> CONSTRAINT fk_emp_dept1 -> FOREIGN KEY(deptId) REFERENCES tb_dept1(id) -> ); Query OK, 0 rows affected (0.37 sec) mysql> DESC tb_emp6; +--------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | | name | varchar(25) | YES | | NULL | | | deptId | int(11) | YES | MUL | NULL | | | salary | float | YES | | NULL | | +--------+-------------+------+-----+---------+-------+ 4 rows in set (1.33 sec)
After the above statement is successfully executed, a foreign key constraint named fk_emp_dept1 is added to table tb_emp6. The foreign key name is deptId, which depends on the primary key id of table tb_dept1.
Note: The foreign key of the secondary table must be related to the primary key of the primary table, and the data types of the primary key and the foreign key must be consistent. For example, both are of type INT, or both are of type CHAR. If such requirements are not met, the "ERROR 1005 (HY000): Can't create table" error will occur when creating the slave table.
Recommended tutorial:mysql tutorial
The above is the detailed content of How to create mysql foreign key constraints. For more information, please follow other related articles on the PHP Chinese website!