search
HomeDatabaseMysql Tutorialwhat is foreign key in mysql

what is foreign key in mysql

Feb 17, 2022 am 11:42 AM
mysqlforeign 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

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;

添加外键

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;

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;

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

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

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

删除MySQL外键

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

ALTER TABLE table_name 
DROP FOREIGN KEY constraint_name;

在上面的声明中:

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

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

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

SHOW CREATE TABLE table_name;

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

SHOW CREATE TABLE products;

以下是语句的输出:

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;

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;

MySQL禁用外键检查

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

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

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

SET foreign_key_checks = 0;

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

SET foreign_key_checks = 1;

【相关推荐: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
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
MySQL's Place: Databases and ProgrammingMySQL's Place: Databases and ProgrammingApr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL: From Small Businesses to Large EnterprisesMySQL: From Small Businesses to Large EnterprisesApr 13, 2025 am 12:17 AM

MySQL is suitable for small and large enterprises. 1) Small businesses can use MySQL for basic data management, such as storing customer information. 2) Large enterprises can use MySQL to process massive data and complex business logic to optimize query performance and transaction processing.

What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?Apr 13, 2025 am 12:16 AM

InnoDB effectively prevents phantom reading through Next-KeyLocking mechanism. 1) Next-KeyLocking combines row lock and gap lock to lock records and their gaps to prevent new records from being inserted. 2) In practical applications, by optimizing query and adjusting isolation levels, lock competition can be reduced and concurrency performance can be improved.

MySQL: Not a Programming Language, But...MySQL: Not a Programming Language, But...Apr 13, 2025 am 12:03 AM

MySQL is not a programming language, but its query language SQL has the characteristics of a programming language: 1. SQL supports conditional judgment, loops and variable operations; 2. Through stored procedures, triggers and functions, users can perform complex logical operations in the database.

MySQL: An Introduction to the World's Most Popular DatabaseMySQL: An Introduction to the World's Most Popular DatabaseApr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

The Importance of MySQL: Data Storage and ManagementThe Importance of MySQL: Data Storage and ManagementApr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system suitable for data storage, management, query and security. 1. It supports a variety of operating systems and is widely used in Web applications and other fields. 2. Through the client-server architecture and different storage engines, MySQL processes data efficiently. 3. Basic usage includes creating databases and tables, inserting, querying and updating data. 4. Advanced usage involves complex queries and stored procedures. 5. Common errors can be debugged through the EXPLAIN statement. 6. Performance optimization includes the rational use of indexes and optimized query statements.

Why Use MySQL? Benefits and AdvantagesWhy Use MySQL? Benefits and AdvantagesApr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

Describe InnoDB locking mechanisms (shared locks, exclusive locks, intention locks, record locks, gap locks, next-key locks).Describe InnoDB locking mechanisms (shared locks, exclusive locks, intention locks, record locks, gap locks, next-key locks).Apr 12, 2025 am 12:16 AM

InnoDB's lock mechanisms include shared locks, exclusive locks, intention locks, record locks, gap locks and next key locks. 1. Shared lock allows transactions to read data without preventing other transactions from reading. 2. Exclusive lock prevents other transactions from reading and modifying data. 3. Intention lock optimizes lock efficiency. 4. Record lock lock index record. 5. Gap lock locks index recording gap. 6. The next key lock is a combination of record lock and gap lock to ensure data consistency.

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools