Table of Contents
Create foreign key
添加外键
删除MySQL外键
MySQL禁用外键检查
Home Database Mysql Tutorial what is foreign key in mysql

what is foreign key in mysql

Feb 17, 2022 am 11:42 AM
mysql foreign key

In MySQL, a foreign key is one or more columns used to establish and strengthen the link between data in two tables. It indicates that a field in one table is referenced by a field in another table. Foreign keys place restrictions on the data in related tables, allowing MySQL to maintain referential integrity.

what is foreign key in mysql

The operating environment of this tutorial: windows7 system, mysql8 version, Dell G3 computer.

The foreign key is relative to the primary key.

Primary key (primary key) An attribute or attribute group that uniquely identifies a row in the table. A table can only have one primary key, but can have multiple candidate indexes. Primary keys often form referential integrity constraints with foreign keys to prevent data inconsistencies. The primary key can ensure that the record is unique and the primary key field is not empty. The database management system automatically generates a unique index for the primary key, so the primary key is also a special index.

Foreign key (foreign key) is one or more columns used to establish and strengthen the link between two table data. A foreign key means that a field in one table is referenced by a field in another table. Foreign keys place restrictions on the data in related tables, allowing MySQL to maintain referential integrity.

Foreign key constraints are mainly used to maintain data consistency between two tables. In short, the foreign key of a table is the primary key of another table, and the foreign key connects the two tables. Under normal circumstances, to delete the primary key in a table, you must first ensure that there are no identical foreign keys in other tables (that is, the primary key in the table does not have a foreign key associated with it).

When defining foreign keys, you need to comply with the following rules:

  • The main table must already exist in the database, or be the table currently being created . If it is the latter case, the master table and the slave table are the same table. Such a table is called a self-referential table, and this structure is called self-referential integrity.

  • A primary key must be defined for the main table.

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

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

  • The number of columns in the foreign key must be the same as the number of columns in the primary key of the main table.

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

Create foreign key

MySQL creates foreign key syntax

The following syntax explains how to CREATE TABLE Define foreign keys in the subtable in the statement.

CONSTRAINT constraint_name
FOREIGN KEY foreign_key_name (columns)
REFERENCES parent_table(columns)
ON DELETE action
ON UPDATE action
Copy after login

Let’s look at the above syntax in more detail:

  • CONSTRAINT clause allows you to define the constraint name for a foreign key constraint. If you omit it, MySQL will automatically generate a name.
  • FOREIGN KEYThe clause specifies the columns in the child table that reference the primary key columns in the parent table. You can place a foreign key name after the FOREIGN KEY clause, or let MySQL create one for you. Note that MySQL automatically creates an index with the name foreign_key_name. The
  • REFERENCES clause specifies references to columns in the parent table and its child tables. The number of columns in the child and parent tables specified in FOREIGN KEY and REFERENCES must be the same. The
  • ON DELETE clause allows you to define how records in the child table perform operations when records in the parent table are deleted. If you omit the ON DELETE clause and delete records in the parent table, MySQL will refuse to delete the associated data in the child table. In addition, MySQL also provides some operations so that you can use additional options, such as ON DELETE CASCADE, when deleting records in the parent table, MySQL can delete records in the child table that reference records in the parent table. If you do not wish to delete related records in the child table, use the ON DELETE SET NULL operation instead. When a record in the parent table is deleted, MySQL will set the foreign key column value in the child table to NULL, provided that the foreign key column in the child table must accept the NULL value . Note that MySQL will reject the delete if the ON DELETE NO ACTION or ON DELETE RESTRICT action is used.
  • ON UPDATE clause allows you to specify what happens to rows in the child table when rows in the parent table are updated. You can omit the ON UPDATE clause to have MySQL reject any updates to rows in the child table when rows in the parent table are updated. The ON UPDATE CASCADE operation allows you to perform a crosstab update, and when a row in the parent table is updated, the ON UPDATE SET NULL operation resets the value in the row in the child table to NULL value. ON UPDATE NO ACTION or UPDATE RESTRICT action rejects any update.

MySQL example of creating a table foreign key

以下示例创建一个dbdemo数据库和两个表:categoriesproducts。每个类别都有一个或多个产品,每个产品只属于一个类别。 products表中的cat_id字段被定义为具有UPDATE ON CASCADEDELETE ON RESTRICT操作的外键。

CREATE DATABASE IF NOT EXISTS dbdemo;

USE dbdemo;

CREATE TABLE categories(
   cat_id int not null auto_increment primary key,
   cat_name varchar(255) not null,
   cat_description text
) ENGINE=InnoDB;

CREATE TABLE products(
   prd_id int not null auto_increment primary key,
   prd_name varchar(355) not null,
   prd_price decimal,
   cat_id int not null,
   FOREIGN KEY fk_cat(cat_id)
   REFERENCES categories(cat_id)
   ON UPDATE CASCADE
   ON DELETE RESTRICT
)ENGINE=InnoDB;
Copy after login

添加外键

MySQL添加外键语法

要将外键添加到现有表中,请使用ALTER TABLE语句与上述外键定义语法:

ALTER table_name
ADD CONSTRAINT constraint_name
FOREIGN KEY foreign_key_name(columns)
REFERENCES parent_table(columns)
ON DELETE action
ON UPDATE action;
Copy after login

MySQL添加外键示例

现在,我们添加一个名为vendors的新表,并更改products表以包含供应商ID字段:

USE dbdemo;

CREATE TABLE vendors(
    vdr_id int not null auto_increment primary key,
    vdr_name varchar(255)
)ENGINE=InnoDB;

ALTER TABLE products 
ADD COLUMN vdr_id int not null AFTER cat_id;
Copy after login

要在products表中添加外键,请使用以下语句:

ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;
Copy after login

现在,products表有两个外键,一个是引用categories表,另一个是引用vendors表。

删除MySQL外键

您还可以使用ALTER TABLE语句将外键删除,如下语句:

ALTER TABLE table_name 
DROP FOREIGN KEY constraint_name;
Copy after login

在上面的声明中:

  • 首先,指定要从中删除外键的表名称。
  • 其次,将约束名称放在DROP FOREIGN KEY子句之后。

请注意,constraint_name是在创建或添加外键到表时指定的约束的名称。 如果省略它,MySQL会为您生成约束名称。

要获取生成的表的约束名称,请使用SHOW CREATE TABLE语句,如下所示:

SHOW CREATE TABLE table_name;
Copy after login

例如,要查看products表的外键,请使用以下语句:

SHOW CREATE TABLE products;
Copy after login

以下是语句的输出:

CREATE TABLE products (
  prd_id int(11) NOT NULL AUTO_INCREMENT,
  prd_name varchar(355) NOT NULL,
  prd_price decimal(10,0) DEFAULT NULL,
  cat_id int(11) NOT NULL,
  vdr_id int(11) NOT NULL,
  PRIMARY KEY (prd_id),
  KEY fk_cat (cat_id),
  KEY fk_vendor(vdr_id),

  CONSTRAINT products_ibfk_2 
  FOREIGN KEY (vdr_id) 
  REFERENCES vendors (vdr_id) 
  ON DELETE NO ACTION 
  ON UPDATE CASCADE,

  CONSTRAINT products_ibfk_1 
  FOREIGN KEY (cat_id) 
  REFERENCES categories (cat_id) 
  ON UPDATE CASCADE
) ENGINE=InnoDB;
Copy after login

products表有两个外键约束:products_ibfk_1products_ibfk_2

可以使用以下语句删除products表的外键:

ALTER TABLE products 
DROP FOREIGN KEY products_ibfk_1;

ALTER TABLE products 
DROP FOREIGN KEY products_ibfk_2;
Copy after login

MySQL禁用外键检查

有时,因为某种原因需要禁用外键检查(例如将CSV文件中的数据导入表中)非常有用。 如果不禁用外键检查,则必须以正确的顺序加载数据,即必须首先将数据加载到父表中,然后再将数据加载导入到子表中,这可能是乏味的。 但是,如果禁用外键检查,则可以按任何顺序加载导入数据。

除非禁用外键检查,否则不能删除由外键约束引用的表。删除表时,还会删除为表定义的任何约束。

要禁用外键检查,请使用以下语句:

SET foreign_key_checks = 0;
Copy after login

当然,可以使用以下语句启用它:

SET foreign_key_checks = 1;
Copy after login

【相关推荐:mysql视频教程

The above is the detailed content of what is foreign key in mysql. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Unable to log in to mysql as root Unable to log in to mysql as root Apr 08, 2025 pm 04:54 PM

The main reasons why you cannot log in to MySQL as root are permission problems, configuration file errors, password inconsistent, socket file problems, or firewall interception. The solution includes: check whether the bind-address parameter in the configuration file is configured correctly. Check whether the root user permissions have been modified or deleted and reset. Verify that the password is accurate, including case and special characters. Check socket file permission settings and paths. Check that the firewall blocks connections to the MySQL server.

The relationship between mysql user and database The relationship between mysql user and database Apr 08, 2025 pm 07:15 PM

In MySQL database, the relationship between the user and the database is defined by permissions and tables. The user has a username and password to access the database. Permissions are granted through the GRANT command, while the table is created by the CREATE TABLE command. To establish a relationship between a user and a database, you need to create a database, create a user, and then grant permissions.

mysql whether to change table lock table mysql whether to change table lock table Apr 08, 2025 pm 05:06 PM

When MySQL modifys table structure, metadata locks are usually used, which may cause the table to be locked. To reduce the impact of locks, the following measures can be taken: 1. Keep tables available with online DDL; 2. Perform complex modifications in batches; 3. Operate during small or off-peak periods; 4. Use PT-OSC tools to achieve finer control.

RDS MySQL integration with Redshift zero ETL RDS MySQL integration with Redshift zero ETL Apr 08, 2025 pm 07:06 PM

Data Integration Simplification: AmazonRDSMySQL and Redshift's zero ETL integration Efficient data integration is at the heart of a data-driven organization. Traditional ETL (extract, convert, load) processes are complex and time-consuming, especially when integrating databases (such as AmazonRDSMySQL) with data warehouses (such as Redshift). However, AWS provides zero ETL integration solutions that have completely changed this situation, providing a simplified, near-real-time solution for data migration from RDSMySQL to Redshift. This article will dive into RDSMySQL zero ETL integration with Redshift, explaining how it works and the advantages it brings to data engineers and developers.

Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Apr 08, 2025 pm 07:12 PM

1. Use the correct index to speed up data retrieval by reducing the amount of data scanned select*frommployeeswherelast_name='smith'; if you look up a column of a table multiple times, create an index for that column. If you or your app needs data from multiple columns according to the criteria, create a composite index 2. Avoid select * only those required columns, if you select all unwanted columns, this will only consume more server memory and cause the server to slow down at high load or frequency times For example, your table contains columns such as created_at and updated_at and timestamps, and then avoid selecting * because they do not require inefficient query se

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

Can mysql run on android Can mysql run on android Apr 08, 2025 pm 05:03 PM

MySQL cannot run directly on Android, but it can be implemented indirectly by using the following methods: using the lightweight database SQLite, which is built on the Android system, does not require a separate server, and has a small resource usage, which is very suitable for mobile device applications. Remotely connect to the MySQL server and connect to the MySQL database on the remote server through the network for data reading and writing, but there are disadvantages such as strong network dependencies, security issues and server costs.

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

See all articles