Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The method of setting Foreign key constraint by MySQL

2025-03-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

This article is about how MySQL sets foreign key constraints. The editor thought it was very practical, so I shared it with you as a reference. Let's follow the editor and have a look.

The MySQL foreign key constraint (FOREIGN KEY) is used to establish a link between the data of two tables, which can be one or more columns. A table can have one or more foreign keys.

The foreign key corresponds to referential integrity. The foreign key of a table can be null. If it is not null, the value of each foreign key must be equal to a value of the primary key in another table.

A foreign key is a field of a table, not the primary key of this table, but corresponds to the primary key of another table. After a foreign key is defined, rows with associated relationships in another table are not allowed to be deleted.

The main function of foreign keys is to maintain the consistency and integrity of data. For example, the primary key of the department table tb_dept is id, and there is a key deptId associated with this id in the employee table tb_emp5. Primary table (parent table): for two tables that have an associated relationship, the table with the primary key in the associated field is the primary table. From the table (child table): for two tables that have an associated relationship, the table where the foreign key in the associated field is located is the slave table.

Select the field that sets the MySQL foreign key constraint

When defining a foreign key, you need to follow the following rules:

The parent table must already exist in the database or the table that is currently being created. In the latter case, the parent and child tables are the same table, and such a table is called a self-reference table, and this structure is called self-referential integrity.

You must define a primary key for the parent table.

The primary key cannot contain null values, but null values are allowed in foreign keys. That is, as long as each non-null value of the foreign key appears in the specified primary key, the content of the foreign key is correct.

Specify a column name or a combination of column names after the table name of the parent table. This column or combination of columns must be the primary or candidate key of the parent table.

The number of columns in the foreign key must be the same as that in the primary key of the parent table.

The data type of the column in the foreign key must be the same as the corresponding column in the parent table primary key.

Set foreign key constraints when creating a table

Use the FOREIGN KEY keyword to create a foreign key in the data table. The specific syntax rules are as follows:

[CONSTRAINT] FOREIGN KEY field name [, field name 2,...] REFERENCES primary key column 1 [, primary key column 2, …]

Among them: the foreign key name is the name of the defined foreign key constraint, and there cannot be a foreign key with the same name in a table; the field name represents the field column to which the child table needs to add foreign key constraints; the primary table name is the name of the table on which the foreign key of the quilt table depends; the primary key column represents the primary key column or column combination defined in the primary table.

Example: to show the foreign key relationship between tables, this example creates a department table tb_dept1 in the test_db database with the following table structure.

The result of the SQL statement that creates the tb_dept1 is shown below.

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 and associate its key deptId as the foreign key to the primary key id of the table tb_dept1. The SQL statement entered and the result of the run are shown below.

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 executed successfully, a foreign key constraint named fk_emp_dept1 is added to the table tb_emp6, and the foreign key name is deptId, which depends on the primary key id of the table tb_dept1.

Tip: Association refers to the relationship between related tables in a relational database. It is represented by the same attribute or group of attributes. The foreign key of the child table must be associated with the primary key of the parent table, and the data types of the associated fields must match. If the type is different, the error "ERROR 1005 (HY000): Can't create table'database.tablename' (errno:150)" will occur when creating the child table.

Add a foreign key constraint when modifying a table

The syntax rules for adding foreign key constraints when modifying a datasheet are:

ALTER TABLE ADD CONSTRAINT FOREIGN KEY () REFERENCES ()

Example: modify the data table tb_emp2, set the field deptId to the foreign key, and associate it with the primary key id of the data table tb_dept1. The SQL statement entered and the running result are shown below.

Mysql > ALTER TABLE tb_emp2-> ADD CONSTRAINT fk_tb_dept1-> FOREIGN KEY (deptId)-> REFERENCES tb_dept1 (id) Query OK, 0 rows affected (1.38 sec) Records: 0 Duplicates: 0 Warnings: 0mysql > SHOW CREATE TABLE tb_emp2\ Graph * 1. Row * * Table: tb_emp2Create Table: CREATE TABLE `tb_ emp2` (`id` int (11) NOT NULL, `name` varchar (30) DEFAULT NULL, `deptId` int (11) DEFAULT NULL `salary` float DEFAULT NULL, PRIMARY KEY (`id`), KEY `fk_tb_ dept1` (`deptId`), CONSTRAINT `fk_tb_ dept1` FOREIGN KEY (`deptId`) REFERENCES `tb_ dept1` (`id`) ENGINE=InnoDB DEFAULT CHARSET=gb23121 row in set (0.12 sec)

Delete foreign key constraint

Foreign keys defined in the database can be deleted if they are no longer needed. Once the foreign key is deleted, the relationship between the master table and the slave table will be disassociated. The syntax format for deleting a foreign key in MySQL is as follows:

ALTER TABLE DROP FOREIGN KEY

Example: delete the foreign key constraint fk_tb_dept1 from the data table tb_emp2, and enter the SQL statement and run the result as shown below.

Mysql > ALTER TABLE tb_emp2-> DROP FOREIGN KEY fk_tb_dept1 Query OK, 0 rows affected (0.19 sec) Records: 0 Duplicates: 0 Warnings: 0mysql > SHOW CREATE TABLE tb_emp2\ Graph * 1. Row * * Table: tb_emp2Create Table: CREATE TABLE `tb_ emp2` (`id` int (11) NOT NULL, `name` varchar (30) DEFAULT NULL, `deptId` int (11) DEFAULT NULL `salary` float DEFAULT NULL, PRIMARY KEY (`id`), KEY `fk_tb_ dept1` (`deptId`) ENGINE=InnoDB DEFAULT CHARSET=gb23121 row in set (0.00 sec)

As you can see, FOREIGN KEY no longer exists in tb_emp2, and the original foreign key constraint named fk_emp_dept was deleted successfully.

Thank you for reading! So much for sharing the method of setting foreign key constraints on MySQL. I hope the above content can be of some help to you, so that you can learn more knowledge. If you think the article is good, you can share it and let more people see it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 235

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report