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

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

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.

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.

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

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

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

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 key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

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.
