Table of Contents
外键用来干什么
外键的使用规则
Home Database Mysql Tutorial MySQL中的外键是什么、有什么作用_MySQL

MySQL中的外键是什么、有什么作用_MySQL

Jun 01, 2016 pm 01:08 PM

Mysql外键

本文参加博文大赛,如果您满意的话麻烦点击这里给我投票原微笑,查看原文点击这里.最近自学数据库MySQL,然后有个疑问,一直不得其解,查询了相关资料,最后还是没有解决。
我的疑问是 "使用外键约束" ,然后我对 "外键" 这个词不是很理解,查询相关资料都是讲一些术语,说外键的主要作用是:保持数据的一致性、完整性。听得我是一头雾水。

关于外键,我有自己的一些理解,但是不晓得是否正确,举个例子来表达我的看法:假如现在需要建立一个表,一个什么样的表呢?一个班级的学生个人信息表:

/

所以在设计的时候,就给表1添加一个外键,这个外键就是表2中的学号字段,那么这样表1就是主表,表2就是子表。所以结合2张表就能保持数据的一致性、完整性(估计就是还原成原来的那张大表吧)。
借着这个例子再谈谈外键的一些事项:
1、表1可以有一个或者多个外键,也可以没有。(如果表1有多个外键可不可以是这样的情况,表2中的多个字段是表1的外键;或者说表1的多个外键是在多个表中)
2、这个外键可以不是表1的主键,但必须是子表的主键。(简单的说就是,如果一个字段是某个表的外键时,那么该字段必须是主键)

以上就是我个人对外键的理解。

----------------------------------------解---答---纠---正-----------------------------------------

什么是外键

+-------+ ref +-------+
| sub | ------> | main |
+-------+ +-------+

从表(sub)的某列引用(ref)主表(main)的某列的值。比如学生表有个学生编号(sid),分数表中的学生列(stu)引用学生表的学 生编号,此时对于分数表的 stu 来说,学生表的 sid 就是外键。从表也叫外键表,主表也叫主键表、外表,列也叫字段。

所以在设计的时候,就给表1添加一个外键,这个外键就是表2中的学号字段,那么这样表1就是主表,表2就是子表

你的主从关系理解颠倒了。你的图中,表1的确是主表,表2是子表,但不是叫做给表1添加一个外键,而是给表2添加一个外键,表2中的学号 字段就叫外键,它是表1学号字段的主键。你可以这样说:表1的学号字段是表2的外键。

外键用来干什么

你贴的图片已经解释了。为了一张表记录的数据不要太过冗余。这和软件工程的模块化思想差不多类似,只不过在数据库中是对表关系进行解耦,尽量让表 记录的数据单一化。就如你贴的图片中,把成绩和学生信息放在一张表中就太冗余了,成绩完全可以以学生的id作为区分标识。

为什么说外键能保持数据的一致性、完整性

你想想,你的图中的第一章表分割成了表1和表2,表2的学号引用了表1的学号字段作为外键,如果不建立外键,只是和表1一样单纯性 地设立一个学号字段,那么和建立外键有什么区别呢?

比如表1中张三的学号为20140900001,那么我在表2中插数据的时候在学号字段插20140900001来记录张三的成绩不也是做到了表 的解耦了吗?

这里存在的问题是,在不设置外键的情况下,表2的学号字段和表1的学号字段是没有关联的。只是你自己认为他们有关系而已,数据库并 不认为它俩有关系。也就是说,你在表2的学号字段插了一个值(比如20140999999),但是这个值在表1中并没有,这个时候,数据库还是允 许你插入的,它并不会对插入的数据做关系检查。然而在设置外键的情况下,你插入表2学号字段的值必须要求在表1的学号字段能找到。 同时,如果你要删除表1的某个学号字段,必须保证表2中没有引用该字段值的列,否则就没法删除。这就是所谓的保持数据的一致性和完整性。你想,如 果表2还引用表1的某个学号,你却把表1中的这个学号删了,表2就不知道这个学号对应的学生是哪个学生。数据的一致性还包括数据类型的一致性(这 个见下面就知道了)。

外键的使用规则

从表的字段必须与外键类型相同(如上,分数表 stu 的类型必须和学生表 sid 的类型相同,比如都是 int(10) 类型)外键必须是主表的唯一键(如上,学生表 sid 是主键,而主键是唯一的,所以可以作为分数表 stu 的外键)有关联的字段(如上,分数表之所以使用学生表的 sid 是因为两者有关联,分数表记录的是学生的分数,而学生可以用 sid 来唯 一标识)避免使用复合键(也就是说从表可以同时引用多个外表的字段作为一个外键,一般不推荐这种做法)

你的问题

如果表1有多个外键可不可以是这样的情况,表2中的多个字段是表1的外键;或者说表1的多个外键是在多个表中

都可以。因为表1的外键不一定是表2的主键,也可以是唯一键(UNIQUE)。比如表2有个主键 A,有个唯一键 B,表1两个字段 A' 和 B’ 分别引用表2的 A 和 B,这就是多对多的关系了。再或者表2主键 A,表3主键 B,表1的两个字段 A' 和 B' 分别引用表2的 A 和表3 的 B。

这个外键可以不是表1的主键,但必须是子表的主键。(简单的说就是,如果一个字段是某个表的外键时,那么该字段必须是主键)

因为你前面就理解错了,所以这句话本身就是错的。对于从表来说,外键不一定需要作为从表的主键,外键也不一定是外表的主键,外表的唯一键就可以作 为从表的外键。

再给一张图以帮助理解

/

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

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.

Explain the role of InnoDB redo logs and undo logs. Explain the role of InnoDB redo logs and undo logs. Apr 15, 2025 am 12:16 AM

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

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's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

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

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

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 vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

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.

How does MySQL index cardinality affect query performance? How does MySQL index cardinality affect query performance? Apr 14, 2025 am 12:18 AM

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

MySQL: From Small Businesses to Large Enterprises MySQL: From Small Businesses to Large Enterprises Apr 13, 2025 am 12:17 AM

MySQL is suitable for small and large enterprises. 1) Small businesses can use MySQL for basic data management, such as storing customer information. 2) Large enterprises can use MySQL to process massive data and complex business logic to optimize query performance and transaction processing.

See all articles