Table of Contents
Database design paradigm
Key
Inner join
外连接
Home Database Mysql Tutorial MySQL multi-table association query example analysis

MySQL multi-table association query example analysis

May 28, 2023 pm 01:32 PM
mysql

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)
Copy after login

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    
 )
Copy after login

往表中填入数据, 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   -- 查询条件
Copy after login

结果 :

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
Copy after login

查询结果如下 :

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
Copy after login

查询结果 : 

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

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

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.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

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'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

MySQL and SQL: Essential Skills for Developers MySQL and SQL: Essential Skills for Developers Apr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

Monitor Redis Droplet with Redis Exporter Service Monitor Redis Droplet with Redis Exporter Service Apr 10, 2025 pm 01:36 PM

Effective monitoring of Redis databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a powerful utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you seamlessly build monitoring solutions. By studying this tutorial, you will achieve fully operational monitoring settings

See all articles