search
HomeDatabaseMysql TutorialMySQL multi-table association query example analysis

Database design paradigm

There are currently five paradigms in database design. Generally, our database only needs to meet the first three paradigms

The first paradigm: ensure that each column remains atomic

What is atomicity? It means that it cannot be subdivided. For example, the contact information below is

MySQL multi-table association query example analysis

. The contact information includes QQ, WeChat, phone, etc. Obviously, this column does not satisfy atomicity. , if it is a separate QQ or phone number, there is only one that satisfies the first normal form

Second normal form: To have a primary key, other fields are required to depend on the primary key

Why is the primary key so important? We can understand it this way, if the table is regarded as a team, then the primary key is the flag of the team

• Without the primary key, there is no uniqueness. Without uniqueness, this row of records cannot be located in the collection. So we need the primary key.

Why do other fields need to rely on the primary key? Because there is no way to determine their location without relying on the primary key. More importantly, the row of records composed of other fields represents the same thing as the primary key, and the primary key is unique. They only need to depend on the primary key, and they become unique.

Third Normal Form: The third normal form is to eliminate transitive dependencies and facilitate understanding. It can be regarded as "eliminating redundancy"

How to understand this? See the following example

MySQL multi-table association query example analysis

If we design a table like the above, it looks normal, but we split the table up

MySQL multi-table association query example analysis

If we do this, it will be much clearer. We directly associate the two tables through the product number. In every aspect, it is much better than squeezing them all into one table.

Key

We know that there is a primary key, which is equivalent to the identifier of the table, so what about the foreign key?

● Foreign key: refers to a record in another data table.

● The foreign key column type is consistent with the primary key column type. The association/reference relationship between data tables is established by relying on the specific primary key (primary key) and foreign key (foreign key)

Syntax:

Add foreign key constraints
ALTER TABLE table name ADD [CONSTRAINT constraint name] FOREIGN KEY (foreign key column)
REFERENCES associated table (primary key);
Delete the foreign check key ALTER TABLE table name DROP FOREIGN KEY foreign key constraint name

We mentioned in the above example of the third normal form that to eliminate redundancy and associate two tables through a certain column, then We usually set this column that connects two tables as a foreign key

However, if we need to query related information between two tables, we may not necessarily use foreign key constraints

  • If two tables are associated with a query, we do not add a foreign key constraint. We call this a weak reference.

  • If a foreign key constraint is added, then it It is a strong reference

So what is the difference between these two references?

We know that when we use foreign keys, the foreign keys are located in the secondary table. The key points to the primary key of the main table, so a constraint is established between the two tables. At this time, we cannot modify the values ​​associated with the main table or the slave table at will. This is a strong reference

1. When there are no corresponding records in the master table, records cannot be added to the slave table

2. Values ​​in the master table cannot be changed, resulting in orphaned records in the slave table

3 , The slave table has records corresponding to the master table, and the row cannot be deleted from the master table

4. Before deleting the master table, delete the slave table first

Weak references allow us to modify the association at will Values ​​between

-- 创建学生表
CREATE TABLE student(
    id INT PRIMARY KEY AUTO_INCREMENT,
    num INT,
    NAME VARCHAR(20),
    sex CHAR(1),
    gradeId INT   -- 从表外键列
)
-- 创建年级表
CREATE TABLE grade(
    -- 主表主键列
    id INT PRIMARY KEY AUTO_INCREMENT,
    NAME VARCHAR(20)
)     
-- 添加外键约束
ALTER TABLE student ADD CONSTRAINT fk_grade 
      FOREIGN KEY(gradeId) REFERENCES grade(id)

Create and add data to the main table:

MySQL multi-table association query example analysis

Create and add data to the slave table:

MySQL multi-table association query example analysis

As you can see, a foreign key constraint has been added to the gradeId field

At this time we try to delete a column of the main table:

MySQL multi-table association query example analysis

Yes See, you cannot change the main table at will. Once changed, the data in the slave table will be isolated

Inner join

MySQL multi-table association query example analysis

##●● Query the intersection data in the two tables that meet the conditions

Syntax:

Select results from Table 1, Table 2 where Table 1.column1 = Table 2.column2

Inner joins include equal joins, non-equivalent joins, and self-joins. Here we mainly discuss self-joins

Cartesian product phenomenon: Table 1 has m rows, Table 2 has n rows, the result =m*n

What is self-connection? It means that you associate yourself with yourself and do a Cartesian product with yourself. This may not be easy to understand. Here is an example:

我们平时在淘宝网购填地址的时候, 都是采用选择的方式, 先选择省,然后是省下面的市, 接着是市下面的区(县) ,它们都是在数据库中存着, 如何去实现这个功能呢 ? 

有人可能会说, 建三张表相互关联即可 , 但实际是 , 我们采用自连接的方式 , 一张表即可实现

CREATE TABLE demo(     -- 建立demo表
    id INT PRIMARY KEY,
    NAME VARCHAR(50),
    pid INT    
 )

往表中填入数据, pid为关联上一级的id

MySQL multi-table association query example analysis

-- 自连接 
-- 在多表关系中我们需要定义别名来区分
SELECT d1.name,d2.name,d3.name FROM demo d1 
            INNER JOIN demo d2 ON d1.id=d2.pid  --自连接条件
            INNER JOIN demo d3 ON d2.id=d3.pid  --自连接条件
  WHERE d3.id=6101011   -- 查询条件

结果 : 

MySQL multi-table association query example analysis

外连接

外连接又分为左外连接与右外连接

先看左外连接 : 

MySQL multi-table association query example analysis

语法 

select 结果 from 表1 left join 表 2 on 表1.column1 = 表 2.column2 

左连接和内连接有什么不同呢?  通过两幅图我们就可以看出 ,内连接是取了两张表的共同部分 , 而左连接是取了左边表的全部(包括两张表的共同部分)

也就是说, 不仅查询两张表的共同部分, 并且左边表会被全部查询出来

我们通过上面外键所建的表来演示 , 为了演示方便,我们为student表再添加一列数据

MySQL multi-table association query example analysis

可以看到, 此时第五列并没有去关联grade表

-- 左外连接查询
SELECT * FROM student s 
     LEFT JOIN grade g ON s.gradeId= g.id

查询结果如下 : 

MySQL multi-table association query example analysis

 那么说到这, 右外连接也就不难理解了 , 每次都会完整的查询右边的表

MySQL multi-table association query example analysis

同样我们再为grade添加一条无关联的数据

MySQL multi-table association query example analysis

语法 :

 select 结果 from 表1 right join 表2 on 表1.column1 = 表2.column2 

-- 右外连接查询
SELECT * FROM student s 
     RIGHT JOIN grade g ON s.gradeId= g.id

查询结果 : 

MySQL multi-table association query example analysis

可以看到, 右表被完全查询

The above is the detailed content of MySQL multi-table association query example analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 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.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

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 Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools