Table of Contents
Why use outer connections
Introduction to outer joins
Left joins and right joins
Outer join exercise ②
Home Database Mysql Tutorial How to use outer joins of data tables in MySQL

How to use outer joins of data tables in MySQL

Jun 03, 2023 pm 03:02 PM
mysql

Why use outer connections

Before explaining why "outer connections" are used, let's take a look at a record. (As follows:)

How to use outer joins of data tables in MySQL

As Zhang San in the table does not have a department number, we will temporarily classify him as a "temporary worker" without a fixed department establishment.

In such a scenario, problems arise. When we want to query the name of each employee and the department to which he belongs, in the case of using inner join, because our link condition is ` "Department Number" of "Employee Table" = "Department of "Department Table" Number", "Zhang San" will be missed. Although "Zhang San" does not have a "department number", he is also a member of the company as a "temporary worker", so the syntax of external joins must be introduced to solve this problem, otherwise some logical data will be lost.

Introduction to outer joins

The difference between outer joins and inner joins:

Only records that meet the connection conditions will appear in the result of the inner join, and records that do not meet the connection conditions will appear It will never appear in the result set.

Regardless of whether the data connection conditions are met, outer connections will be displayed in the result set in a special way. (For example, querying employee department number information mentioned above, because "Zhang San" does not have a department number, if an inner join is used, "Zhang San" does not meet the "connection conditions" and will not appear in the result set. ; Change to "outer join" and you will not miss it.)

Examples of outer joins are as follows

SELECT 
	e.empno, e.ename, d.dname
FROM
	t_emp e
LEFT JOIN t_dept d ON e.deptno = d.deptno;

-- 在连接的时候仍然是链接 "员工表" 与 "部门表" ,只不过连接关键字由 "JOIN" 变成了 "LEFT JOIN" (下文再为大家详细解释)
-- 两张表的连接条件还是使用 "ON" 关键字去连接的 , 连接条件依然是 "员工表" 的 "部门编号" = "部门表" 的 "部门编号" 

-- LEFT JOIN 为 "外连接" 的 "左外连接" ;(在 "外连接" 中,是分为 "左外连接" 与 "右外连接" 的)

-- 在该SQL语句中 "LEFT JOIN" 左右各有数据表  "t_emp e" 与 "t_dept d" 
-- 所以这里的 "左连接" 的意思就是:保留 左表 的所有记录,然后与 右表 去连接,如果 右表 有符合条件的记录,则正常连接即可;
-- 如果 右表 没有符合条件的连接记录, 右表 则展示 "NULL" 值与 "左表" 去匹配
Copy after login

How to use outer joins of data tables in MySQL

Left joins and right joins

"Left outer join" means that during the connection operation, all records in the left table are retained and connected to the right table. The left table will be connected to the right table. If there are records that meet the conditions in the right table; if there are no records that meet the conditions in the right table, "NULL" will be used to connect the left table.

The difference from "left join" is "right join". "Right join" is the opposite of "left join". It retains all the records in the right table and joins the qualified records in the left table; the same , if the left table does not have records that meet the conditions, use "NULL" to join the right table.

Right join SQL statement example:

SELECT 
	e.empno, e.ename, d.dname
FROM
	t_dept d
RIGHT JOIN t_emp e ON e.deptno = d.deptno;

-- 这里有个需要注意的地方,就是相较于上文中的 "左连接" ,这里的 "右连接" 左右两张的表的位置做了调换
Copy after login

How to use outer joins of data tables in MySQL

Here, you can see that you can still find out that "Zhang San" does not have a "department number" record of. So the difference between "left join" and "right join" is not very big.

Outer join exercise ①

Query the name of each department and the number of people in the department?

This question seems simple, but there are two difficulties in it, and there are also areas where mistakes are easy to make. For details, see the SQL statement examples and schematic diagram below.

SELECT 
    d.deptno, d.dname, COUNT(*)
FROM
    t_dept d LEFT JOIN t_emp e 
ON d.deptno = e.deptno
GROUP BY d.deptno;
Copy after login

How to use outer joins of data tables in MySQL

OK, this is where the problem starts.

Everyone pay attention to the "40" - "OPERATIONS" department here. There is actually no one in this department, that is, the number of people is "0", but strangely, when statistics are performed here, there is The number of people counted is "1". Why is this?

This is because when we use grouping, we use "left join" and retain all the data in the left table, so we follow the left table's "deptno" for grouping. (Because the records of the left table are retained, the grouping also needs to be grouped according to the left table. The next key is "COUNT(*)", which will count the number of all valid records. So when all the records of the left table "t_dept" When the record is connected to the right table "t_emp", the right table will use the "NULL" value to connect to the left table "t_dept". After the connection is completed, it will be a valid record. Since it is a valid record, then "COUNT(*)" The statistical result is "1".

So, it is understandable that the statistical result of 40 departments is "1", but this result is not what we want. How to go about it How to solve it? Refer to the SQL statement below.

SELECT 
    d.deptno, d.dname, COUNT(e.deptno)
FROM
    t_dept d LEFT JOIN t_emp e 
ON d.deptno = e.deptno
GROUP BY d.deptno;
Copy after login

How to use outer joins of data tables in MySQL

This SQL statement is still very good. There are many details and unconsidered situations. Only if you really write it once Only when these attacks will be noticed.

Outer join exercise ②

Retrieve the department name and number of people. For employees who do not have a department, use "NULL" instead of the department name. (This actually refers to "Zhang San")

Maybe you will think that what you just used is a "left outer join" to retain all the records in the department table. Isn't it just a "right" outer join? In fact... . It’s not that simple.

The SQL statement of this exercise needs to be implemented using the "UNION" keyword. Use the "UNION" keyword to merge the result sets of multiple query statements (to exclude duplicates) content).

"UNION"关键字 在 SQL 语句中的用法如下:

(SQL查询语句) UNION (SQL查询语句) -- 如果存在多条查询语句的话,可以继续使用 UNION 关键字 连接

PS:这里需要注意一下,“UNION” 合并多少个结果集其实无所谓,关键是这些结果集的字段数量和字段的名称必须要相同 。如果说第一个 SQL 查询语句返回的是 10个 字段,第二个返回的是 2个字段 ,这种情况是完全没办法合并的。

(SELECT 
	d.deptno, d.dname, COUNT(e.deptno)
FROM
	t_dept d LEFT JOIN t_emp e 
ON d.deptno = e.deptno
GROUP BY d.deptno)
UNION
(SELECT 
	d.deptno, d.dname, COUNT(*)
FROM
	t_dept d RIGHT JOIN t_emp e 
ON d.deptno = e.deptno
GROUP BY d.deptno);

-- 第一个查询语句,得到的结果集是各个部门的人数。
-- 第二个查询语句,得到的结果集是隶属于各个部门的人数,但是因为 "张三" 是一个没有部门所属的 "临时工"
-- 所以两个查询语句的结果集合并之下没救如下图所示。
Copy after login

How to use outer joins of data tables in MySQL

The above is the detailed content of How to use outer joins of data tables in MySQL. 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