如何在MySQL数据库中定义外键
定义数据表 假如某个电脑生产商,它的数据库中保存着整机和配件的产品信息。用来保存整机产品信息的表叫做pc;用来保存配件供货信息的表叫做parts。 在pc表中有一个字段,用来描述这款电脑所使用的CPU型号;在parts表中相应有一个字段,描述的正是CPU的型号
定义数据表
假如某个电脑生产商,它的数据库中保存着整机和配件的产品信息。用来保存整机产品信息的表叫做pc;用来保存配件供货信息的表叫做parts。
在pc表中有一个字段,用来描述这款电脑所使用的CPU型号;在parts表中相应有一个字段,描述的正是CPU的型号,我们可以把它想成是全部CPU的型号列表。
很显然,这个厂家生产的电脑,其使用的CPU一定是供货信息表(parts)中存在的型号。这时,两个表中就存在一种约束关系(constraint)——pc表中的CPU型号受到parts表中型号的约束。
首先我们来创建parts表:
<p>CREATE TABLE parts (<br>... 字段定义 ...,<br>model VARCHAR(20) NOT NULL,<br>... 字段定义 ...<br>);</p> Copy after login |
接下来是PC表:
<p>CREATE TABLE pc (<br>... 字段定义 ...,<br>cpumodel VARCHAR(20) NOT NULL,<br>... 字段定义 ...<br>};</p> Copy after login |
设置索引
若要设置外键,在参照表 (referencing table,即pc表) 和被参照表(referenced table,即parts表)中,相对应的两个字段必须都设置索引(index)。
对parts表:
<p>ALTER TABLE parts ADD INDEX idx_model (model);</p> Copy after login |
这句话的意思是,为parts表增加一个索引,索引建立在model字段上,给这个索引起个名字叫idx_model。
对pc表也类似:
<p>ALTER TABLE pc ADD INDEX idx_cpumodel (cpumodel);</p> Copy after login |
事实上这两个索引可以在创建表的时候就设置。这里只是为了突出其必要性。
定义外键
下面为两张表之间建立前面所述的那种“约束”。因为pc的CPU型号必须参照parts表中的相应型号,所以我们将pc表的cpumodel字段设置为“外键”(FOREIGN KEY),即这个键的参照值来自于其他表。
<p>ALTER TABLE pc ADD CONSTRAINT fk_cpu_model <br>FOREIGN KEY (cpumodel) <br>REFERENCES parts(model);</p> Copy after login |
第一行是说要为pc表设置外键,给这个外键起一个名字叫做fk_cpu_model;第二行是说将本表的cpumodel字段设置为外键;第三行是说这个外键受到的约束来自于parts表的model字段。
这样,我们的外键就搞好了!如果我们试着CREATE一台pc,它所使用的CPU的型号是parts 表中不存在的,那么MySQL会禁止这台PC被CREATE出来。
级联操作
考虑以下这种情况:
技术人员发现,一个月之前输入到parts表中的某个系列的cpu(可能有很多款)的型号全都输错了一个字母,现在需要改正。我们希望的是,当parts表中那些 Referenced Column 有所变化时,相应表中的 Referencing Column 也能自动更正。
可以在定义外键的时候,在最后加入这样的关键字:
<p>ON UPDATE CASCADE;</p> Copy after login |
即在主表更新时,子表(们)产生连锁更新动作,似乎有些人喜欢把这个叫“级联”操作。
如果把这语句完整的写出来,就是:
<p>ALTER TABLE pc ADD CONSTRAINT fk_cpu_model <br>FOREIGN KEY (cpumodel) <br>REFERENCES parts(model)<br>ON UPDATE CASCADE;</p> Copy after login |
除了CASCADE外,还有RESTRICT(禁止主表变更)、SET NULL(子表相应字段设置为空)等操作。
【相关文章】
- MySQL数据库中用GRANT语句增添新用户
- 分析MySQL的数据类型以及建库策略
- SQL Server中的完整性和外键

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

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Oracle is not only a database company, but also a leader in cloud computing and ERP systems. 1. Oracle provides comprehensive solutions from database to cloud services and ERP systems. 2. OracleCloud challenges AWS and Azure, providing IaaS, PaaS and SaaS services. 3. Oracle's ERP systems such as E-BusinessSuite and FusionApplications help enterprises optimize operations.

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages have advantages in their respective fields such as data analytics, enterprise applications, and system programming.
