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

AI Hentai Generator
Generate AI Hentai for free.

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 query performance can be optimized by building indexes that reduce lookup time from linear complexity to logarithmic complexity. Use PreparedStatements to prevent SQL injection and improve query performance. Limit query results and reduce the amount of data processed by the server. Optimize join queries, including using appropriate join types, creating indexes, and considering using subqueries. Analyze queries to identify bottlenecks; use caching to reduce database load; optimize PHP code to minimize overhead.

Backing up and restoring a MySQL database in PHP can be achieved by following these steps: Back up the database: Use the mysqldump command to dump the database into a SQL file. Restore database: Use the mysql command to restore the database from SQL files.

How to insert data into MySQL table? Connect to the database: Use mysqli to establish a connection to the database. Prepare the SQL query: Write an INSERT statement to specify the columns and values to be inserted. Execute query: Use the query() method to execute the insertion query. If successful, a confirmation message will be output.

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the "MySQL Native Password" plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

To use MySQL stored procedures in PHP: Use PDO or the MySQLi extension to connect to a MySQL database. Prepare the statement to call the stored procedure. Execute the stored procedure. Process the result set (if the stored procedure returns results). Close the database connection.

2024 is the first year of AI mobile phones. More and more mobile phones integrate multiple AI functions. Empowered by AI smart technology, our mobile phones can be used more efficiently and conveniently. Recently, the Galaxy S24 series released at the beginning of the year has once again improved its generative AI experience. Let’s take a look at the detailed function introduction below. 1. Generative AI deeply empowers Samsung Galaxy S24 series, which is empowered by Galaxy AI and brings many intelligent applications. These functions are deeply integrated with Samsung One UI6.1, allowing users to have a convenient intelligent experience at any time, significantly improving the performance of mobile phones. Efficiency and convenience of use. The instant search function pioneered by the Galaxy S24 series is one of the highlights. Users only need to press and hold

Creating a MySQL table using PHP requires the following steps: Connect to the database. Create the database if it does not exist. Select a database. Create table. Execute the query. Close the connection.

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())
