MySQL的外键约束级联删除_MySQL
Mysql外键
bitsCN.comMySQL的外键约束级联删除
在更新数据库时使用外键约束
第一个表存储一些简单博客数据,而第二个表则存放这些博客的有关评论。这例子的巧妙之处在于,它给子表定义了一个外键约束,从而允许我们在博客文章被删除时自动地删除有关的所有评论。下面给出这两个表的定义,它们建立了一个一对多的关系:
01DROP TABLE IF EXISTS `test`.`blogs`;0203CREATE TABLE `test`.`blogs` (0405`id` INT ( 10 ) UNSIGNED AUTO_INCREMENT,0607`title` TEXT ,0809`content` TEXT ,1011`author` VARCHAR ( 45 ) DEFAULT NULL ,1213PRIMARY KEY (`id`)1415) ENGINE = InnoDB DEFAULT CHARSET = utf8;1617 1819DROP TABLE IF EXISTS `test`.`comments`;2021CREATE TABLE `test`.`comments` (2223`id` INT ( 10 ) UNSIGNED AUTO_INCREMENT,2425`blog_id` INT ( 10 ) UNSIGNED DEFAULT NULL ,2627`comment` TEXT ,2829`author` VARCHAR ( 45 ) DEFAULT NULL ,3031PRIMARY KEY (`id`),3233KEY `blog_ind` (`blog_id`),3435CONSTRAINT `comments_ibfk_1` FOREIGN KEY (`blog_id`) REFERENCES `blogs` (`id`) ON UPDATE CASCADE3637) ENGINE = InnoDB DEFAULT CHARSET = utf8;
除了给以上两个InnoDB表定义一些简单字段外,上述的代码还使用了一个外键约束,使得每当父表的“id”键更新时,表comments的相应内容也会级联更新。给父字段“id”定义约束的代码如下所示:
1CONSTRAINT `comments_ibfk_1` FOREIGN KEY (`blog_id`) REFERENCES `blogs` (`id`) ON UPDATE CASCADE
InnoDB引擎除了可以规定根据父表完成的操作对子表进行的级联更新以外,还可以执行其他的操作,包括“NO ACTION”和“RESTRICT”,这样即使父表发生更新或者删除操作,也不会引起对子表的任何操作。
现在,根据上面的MySQL表的定义,填充如下所示的数据:
1INSERT INTO blogs (id, title, content, author) VALUES ( NULL , ' Title of the first blog entry ' , ' Content of the first blog entry ' , ' Tom ' )23INSERT INTO comments (id, blog_id, comment, author) VALUES ( NULL , 1 , ' Commenting first blog entry ' , ' Susan Norton ' ), ( NULL , 1 , ' Commenting first blog entry ' , ' Rose ' )
然后,由于某种原因,我们更新了第一个博客数据,那么只要运行下列SQL语句,与该博客文章有关的所有评论也会随之自动更新:
1UPDATE blogs SET id = 2 , title = ' Title of the first blog entry ' , content = ' Content of the first blog entry ' , author = ' John Doe ' WHERE id = 1
这看起来非常不错,对吧?前面讲过,外键约束容许您将表之间的关系的维护工作委托给数据库层,这意味着编写与数据层交互的应用程序时可以省去不少的代码。
此外,我们也可以触发级联删除操作,这与前面演示的情形非常类似。因此,下面我们继续使用早先定义的两个示例表来演示当某篇博客文章的数据被删除时,如何利用外键约束删除相应的评论。
不使用外键约束时的数据删除
为了说明当父表数据被删除时,外键约束在维护数据库完整性方面发挥的作用,我们将重建前面的例子,这次使用MyISAM表。首先,我们需要定义数据表,具体代码如下所示:
01DROP TABLE IF EXISTS `test`.`blogs`;0203CREATE TABLE `test`.`blogs` (0405`id` INT ( 10 ) UNSIGNED AUTO_INCREMENT,0607`title` TEXT ,0809`content` TEXT ,1011`author` VARCHAR ( 45 ) DEFAULT NULL ,1213PRIMARY KEY (`id`)1415) ENGINE = MyISAM DEFAULT CHARSET = utf8;1617 1819DROP TABLE IF EXISTS `test`.`comments`;2021CREATE TABLE `test`.`comments` (2223`id` INT ( 10 ) UNSIGNED AUTO_INCREMENT,2425`blog_id` INT ( 10 ) UNSIGNED DEFAULT NULL ,2627`comment` TEXT ,2829`author` VARCHAR ( 45 ) DEFAULT NULL ,3031PRIMARY KEY (`id`)3233) ENGINE = MyISAM DEFAULT CHARSET = utf8;
好了,我们已经建好了两个示例表,需要注意的是,它们使用的是默认的MyISAM数据库引擎,所以不支持外键约束。
定义的这两个表构成了博客应用程序的数据层,接下来我们在其中填上一些数据,所用的代码如下所示:
1INSERT INTO blogs (id, title, content, author) VALUES ( NULL , ' Title of the first blog entry ' , ' Content of the first blog entry ' , ' Tom ' )23INSERT INTO comments (id, blog_id, comment, author) VALUES ( NULL , 1 , ' Commenting first blog entry ' , ' Susan Norton ' ), ( NULL , 1 , ' Commenting first blog entry ' , ' Rose ' )
实际上,以上代码片断模拟了博客应用程序运行时,我们发布了博客并有人张贴评论时,程序在表blogs中插入一篇博客文章的有关数据,并在子表中插入有关评论的过程。现在,如果我们删除了这篇博客,那么有关的评论也应该随之删除。
但是,我们该如何去做呢?别急,下面我们以SQL语句为例说明如何完成此任务:
1DELETE FROM blogs WHERE id = 12DELETE FROM comments WHERE blog_id = 1<u></u>
当然,在实际情况下,我们应该通过服务器端语言来执行这两个删除语句,而不是使用原始的SQL命令;但是这里只是举例之用,就不用考虑这么多了。
我想您现在已经弄明白了使用MyISAM表时如何删除博客数据,以及有关的评论。因此,接下来我们将重新构建这个例子,不过这次我们将让数据表使用InnoDB存储引擎和一个简单的外键约束。
使用外键约束时的数据删除
恰如您可以使用外键约束级联更新数据一样,InnoDB表还支持级联删除,这对于维护那些具有特定关系的数据表的一致性极为有用。
下面我们举例说明,现在重新定义两个表,如下所示:
01DROP TABLE IF EXISTS `test`.`blogs`;0203CREATE TABLE `test`.`blogs` (0405`id` INT ( 10 ) UNSIGNED AUTO_INCREMENT,0607`title` TEXT,0809`content` TEXT,1011`author` VARCHAR( 45 ) DEFAULT NULL ,1213PRIMARY KEY (`id`)1415) ENGINE = InnoDB DEFAULT CHARSET = utf8;1617 1819DROP TABLE IF EXISTS `test`.`comments`;2021CREATE TABLE `test`.`comments` (2223`id` INT ( 10 ) UNSIGNED AUTO_INCREMENT,2425`blog_id` INT ( 10 ) UNSIGNED DEFAULT NULL ,2627`comment` TEXT,2829`author` VARCHAR( 45 ) DEFAULT NULL ,3031PRIMARY KEY (`id`),3233KEY `blog_ind` (`blog_id`),3435CONSTRAINT `comments_ibfk_1` FOREIGN KEY (`blog_id`) REFERENCES `blogs` (`id`) ON DELETE CASCADE3637) ENGINE = InnoDB DEFAULT CHARSET = utf8;
现在,组成我们虚构的博客应用程序的数据层的两个表blogs和comments将使用InnoDB存储引擎。这意味着,它们能利用外键约束来删除与某博客有关的所有评论,当该博客被删除的时候。
引起级联删除的SQL语句如下所示:
1CONSTRAINT `comments_ibfk_1` FOREIGN KEY (`blog_id`) REFERENCES `blogs` (`id`) ON DELETE CASCADE
现在,由于这个约束已经施加于blog表的“id”字段,所以在删除博客的同时清除有关评论将非常简单,就像运行一个DELETE命令一样,具体如下所示:
1DELETE FROM blogs WHERE id = 1
我们看到,现在事情变得简单多了。从这个例子您就可以想象得出,当数据层使用利用外键约束在数据库级别维护各表之间关系的完整性和一致性的数据表的时候,开发与这样的数据层交互的应用程序是多么的简单。
bitsCN.com

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

Go language is an efficient, concise and easy-to-learn programming language. It is favored by developers because of its advantages in concurrent programming and network programming. In actual development, database operations are an indispensable part. This article will introduce how to use Go language to implement database addition, deletion, modification and query operations. In Go language, we usually use third-party libraries to operate databases, such as commonly used sql packages, gorm, etc. Here we take the sql package as an example to introduce how to implement the addition, deletion, modification and query operations of the database. Assume we are using a MySQL database.

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

Hibernate polymorphic mapping can map inherited classes to the database and provides the following mapping types: joined-subclass: Create a separate table for the subclass, including all columns of the parent class. table-per-class: Create a separate table for subclasses, containing only subclass-specific columns. union-subclass: similar to joined-subclass, but the parent class table unions all subclass columns.

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

HTML cannot read the database directly, but it can be achieved through JavaScript and AJAX. The steps include establishing a database connection, sending a query, processing the response, and updating the page. This article provides a practical example of using JavaScript, AJAX and PHP to read data from a MySQL database, showing how to dynamically display query results in an HTML page. This example uses XMLHttpRequest to establish a database connection, send a query and process the response, thereby filling data into page elements and realizing the function of HTML reading the database.

Through the Go standard library database/sql package, you can connect to remote databases such as MySQL, PostgreSQL or SQLite: create a connection string containing database connection information. Use the sql.Open() function to open a database connection. Perform database operations such as SQL queries and insert operations. Use defer to close the database connection to release resources.

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.
