Detailed explanation of foreign key constraints in MySQL database
[Introduction] Anyone who has developed a small database-driven web application using MySQL knows that creating, retrieving, updating, and deleting tables in a relational database are relatively simple processes. In theory, as long as you master the usage of the most common SQL statements and become familiar with the server-side scripts you choose to use. Anyone who has developed a small database-driven web application using MySQL knows that the tables of a relational database Creating, retrieving, updating, and deleting operations are relatively simple processes. Theoretically, as long as you master the usage of the most common SQL statements and are familiar with the server-side scripting language you choose to use, it is enough to handle the various operations required on MySQL tables, especially when you use the fast MyISAM database engine. when. But even in the simplest cases, things are more complicated than we think. Below we use a typical example to illustrate. Suppose you are running a blog site that you update almost daily, and the site allows visitors to comment on your posts.
In this case, our database schema should include at least two MyISAM tables, one for storing your blog posts and the other for processing visitor comments. Obviously, there is a one-to-many relationship between these two tables, so we need to define a foreign key in the second table so that the integrity of the database can be maintained when data rows are updated or deleted.
For an application like the one above, not only is maintaining the integrity of the two tables a serious challenge, but the biggest difficulty is that we must maintain their integrity at the application level. . This is the approach taken during development for most web projects that do not require the use of transactions because MyISAM tables provide excellent performance.
Of course, this also comes at a cost. As I said earlier, the application must maintain the integrity and consistency of the database, which means implementing more complex programs. Design logic to handle relationships between various tables. Although database access can be simplified through the use of abstraction layers and ORM modules, as the number of data tables required by an application increases, the logic required to handle them will undoubtedly become more complex.
So, for MySQL, is there any database-level foreign key processing method to help maintain database integrity? Fortunately, the answer is yes! MySQL can also support it InnoDB tables allow us to handle foreign key constraints in a very simple way. This feature allows us to trigger certain actions, such as updating and deleting certain data rows in the table to maintain predefined relationships.
Everything has pros and cons. The main disadvantage of using InnoDB tables is that they are slower than MyISAM, especially in large-scale applications where many tables must be queried. obvious. Fortunately, the MyISAM table in the newer version of MySQL also supports foreign key constraints.
This article will introduce how to apply foreign key constraints to InnoDB tables. In addition, we will use a simple PHP-based MySQL abstract class to create the relevant sample code; of course, you can also use your favorite other server-side language. Now, we start introducing how to apply foreign key constraints to MySQL.
The timing of using foreign key constraints
To be honest, when using an InnoDB table in MySQL, it is not necessary to use foreign key constraints. , however, in order to understand the utility of foreign key constraints in certain situations, we will specifically illustrate it through the code of the example mentioned earlier. It includes two MyISAM tables, used to store blog posts and comments.
When defining the database schema, we need to establish a one-to-many relationship between the two tables by creating a foreign key in the table where the comments are stored to separate the data rows (i.e. comments ) corresponds to a specific blog post. Here is the basic SQL code to create a sample MyISAM table:
DROP TABLE IF EXISTS `test`.`blogs`;
CREATE TABLE `test`.`blogs` (
`id` INT(10) UNSIGNED AUTO_INCREMENT,
`title` TEXT,
`content` TEXT,
`author` VARCHAR(45) DEFAULT NULL,
PRIROSE KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `test`.`comments`;
CREATE TABLE `test`.`comments` (
`id` INT(10) UNSIGNED AUTO_INCREMENT,
`blog_id` INT(10) UNSIGNED DEFAULT NULL,
`comment` TEXT,
`author` VARCHAR(45) DEFAULT NULL,
PRIROSE KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET= utf8;
Above, we just defined two MyISAM tables, which form the data layer of the blog application. As you can see, the first table is called blogs. It consists of some obvious fields, which are used to store the ID, title and content of each blog post, and finally the author. The second table is named comments, which is used to store comments related to each blog post. It uses the ID of the blog post as its foreign key to establish a one-to-many relationship.
So far, our work has been relatively easy, because we have only created two simple MyISAM tables. Next, what we want to do is populate these tables with some records to further demonstrate what should be done in the other table when an entry is deleted in the first table.
Update and maintain the integrity of the database
In the previous part, we created two MyISAM tables to serve as the data layer of the blog application. Of course, the above introduction is still very simple, and we need to discuss it further. To do this, we will populate these tables with some records by using SQL commands as follows:
INSERT INTO blogs (id, title, content, author) VALUES (NULL,'Title of the first blog entry', 'Content of the first blog entry', 'Ian')
INSERT INTO comments (id, blog_id, comment, author) VALUES (NULL, 1, 'Commenting first blog entry', 'Susan Norton'), (NULL, 1, 'Commenting first blog entry', 'Rose Wilson')
The above code actually simulates readers Susan and Rose's first blog entry for us. Blogger made a comment. Suppose now we want to update the first blog with another post. Of course, this situation is possible.
In this case, in order to maintain the consistency of the database, the comments table must also be updated accordingly, either manually or by an application processing the data layer. . For this example, we will use SQL commands to complete the update, as shown below:
UPDATE blogs SET id = 2, title = "Title of the first blog entry", content = 'Content of the first blog entry', author = 'John Doe' WHERE id = 1
UPDATE comments SET blog_id = 2 WHERE blod_id = 1
As mentioned before, because the first blog The content of the data item has been updated, so the comments table must also reflect this change. Of course, in reality, this update operation should be completed at the application layer rather than manually, which means that this logic must be implemented using a server-side language.
In order to complete this operation, PHP can go through a simple sub-process, but in fact, if foreign key constraints are used, the update operation on the comments table is completely Can be delegated to the database.
As mentioned earlier in the article, InnoDB MySQL tables provide seamless support for this function. Therefore, in the later part we will use foreign key constraints to re-create the previous example code.
Cascade update of database
Below, we will restructure the previous example code using foreign key constraints and InnoDB tables (instead of the default MyISAM type). To do this, first redefine the two sample tables so that they can use a specific database engine. To do this, you can use SQL code like this:
DROP TABLE IF EXISTS `test`.`blogs`;
CREATE TABLE `test`.`blogs` (
`id` INT(10) UNSIGNED AUTO_INCREMENT,
`title` TEXT,
`content` TEXT,
`author` VARCHAR(45) DEFAULT NULL,
PRIROSE KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `test`.`comments`;
CREATE TABLE `test`.`comments` (
`id` INT(10) UNSIGNED AUTO_INCREMENT,
`blog_id` INT(10) UNSIGNED DEFAULT NULL,
`comment` TEXT,
`author` VARCHAR(45) DEFAULT NULL,
PRIROSE KEY (`id`),
KEY `blog_ind` ( `blog_id`),
CONSTRAINT `comments_ibfk_1` FOREIGN KEY (`blog_id`) REFERENCES `blogs` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Compared with the previous code, one obvious difference between the code here and the previous code is that these two tables now use the InnoDB storage engine, so they can support foreign key constraints. In addition, we also need to pay attention to the code that defines the comments table:
CONSTRAINT `comments_ibfk_1` FOREIGN KEY (`blog_id`) REFERENCES `blogs` (`id`) ON UPDATE CASCADE
Actually, this statement notifies MySQLMySQL that when the blogs table is updated, the value of the foreign key blog_id in the comments table should also be updated. In other words, what is done here is to let MySQL maintain database integrity in a cascading manner. This means that when a blog is updated, the comments connected to it must also immediately reflect this change. It is important. The important thing is that the implementation of this function is not completed at the application layer.
The two example MySQL tables have been defined. Now, updating these two tables is as simple as running an UPDATE statement, as shown below:
"UPDATE blogs SET id = 2, title = "Title of the first blog entry", content = 'Content of the first blog entry', author = 'John Doe' WHERE id = 1"
As mentioned before, we don’t need to update the comments table because MySQL will handle it all automatically. Additionally, you can have MySQL do nothing when trying to update a row in the blogs table by removing the "ON UPDATE" part of the query or specifying "NO ACTION" and "RESTRICT". Of course, you can also let MySQL do other things, which will be introduced in subsequent articles.
Through the above introduction, I think everyone has a clear understanding of how to use foreign key constraints in conjunction with InnoDB tables in MySQL. Of course, you can also further write the upcoming code to further develop your understanding of this convenient database feature.
The above is the detailed content of Detailed explanation of foreign key constraints in MySQL database. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

DeepSeekAI Tool User Guide and FAQ DeepSeek is a powerful AI intelligent tool. This article will answer some common usage questions to help you get started quickly. FAQ: The difference between different access methods: There is no difference in function between web version, App version and API calls, and App is just a wrapper for web version. The local deployment uses a distillation model, which is slightly inferior to the full version of DeepSeek-R1, but the 32-bit model theoretically has 90% full version capability. What is a tavern? SillyTavern is a front-end interface that requires calling the AI model through API or Ollama. What is breaking limit

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7
