MySQL database - multi-table query (3) - self-join, joint query, subquery

Table of contents

self-connection 

Query syntax

Self-connection demonstration

Union query

Query syntax

subquery

introduce

scalar subquery

column subquery

row subquery

Table subquery


self-connection 

Through the previous study, we already have a certain understanding of connections. Self-joining, in layman's terms, means joining itself, that is, querying a table multiple times.

In the process of self-joining, one table needs to be treated as two tables, that is, aliased.

Query syntax

SELECT 字段列表 FROM 表A 别名A JOIN 表A 别名B ON 条件...;

Self-join query can be an inner join query or an outer join query.

Self-connection demonstration

1. Query the names of employees and their leaders

We observe the table, find the connection conditions corresponding to the questions, and sort them out:

  • Table structure: emp
  • Connection condition: id = managerid
select a.name '员工',b.name '领导' from emp a ,emp b where a.managerid = b.id;

search result:

2. Query the names of all employees and their leaders. If the employee does not have a leader, you also need to query them.

If employees do not have a leader, they need to be queried. Outer joins must be used, either left or right outer joins.

The table structure and connection conditions remain unchanged.

select a.name '员工',b.name '领导' from emp a left outer join emp b on a.managerid = b.id;

search result: 

Union query

Let’s look at a little knowledge point

Union query-union, union all

For union queries, the results of multiple queries are combined to form a new query result set.

Query syntax

SELECT 字段列表 FROM 表A ...
UNION [ALL]
SELECT 字段列表 FROM 表B ...;

For joint queries, the number of columns in multiple tables must be consistent, and the field types must also be consistent.

Union all will merge all the data directly together, and union will deduplicate the merged data.

subquery

introduce

1. Concept

Nesting a SELECT statement in an SQL statement is called a nested query , also known as a subquery .

SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2);

 The statement outside the subquery can be any of INSERT/UPDATE/DELETE/SELECT.

2. According to the different results of the subquery, it is divided into:

  • Scalar subquery (subquery result is a single value)
  • Column subquery (subquery result is one column)
  • Row subquery (subquery result is one row)
  • Table subquery (subquery results are multiple rows and columns)

3. According to the subquery position, it is divided into: after WHERE, after FROM, and after SELECT.

scalar subquery

The result returned by a subquery is a single value (number, string, date, etc.). In its simplest form, this subquery is called a scalar subquery.

Commonly used operators: = <> < <= > >=

Let’s do it in practice:

1. Query all employee information of "Sales Department"

The query is first divided into two steps: first, query the department ID of the sales department, and second, query the employee information corresponding to the department ID;

Nest it again and use scalar subqueries.

-- 1.查询销售部的所有员工信息
-- a.查询'销售部'的部门ID
select id from dept where name = '销售部'; -- 返回结果为 4

-- b.根据销售部部门ID,查询员工信息
select * from emp e where e.dept_id = 4;

-- 标量子查询
select * from emp e where e.dept_id = (select id from dept where name = '销售部');

2. Query employee information after 'Fang Dongbai' joined the company

Solved by the same method

-- 2.查询在'方东白'入职之后的员工信息
-- a.查询'方东白'的入职日期
select entrydate from emp where name = '方东白';

-- b.查询指定入职日期之后入职的员工信息
select * from emp where entrydate > '2009-02-12';

-- 标量子查询
select * from emp where entrydate > (select entrydate from emp where name = '方东白');

column subquery

The result returned by a subquery is a column (can be multiple rows). This subquery is called a column subquery .

Commonly used operators: IN, NOT IN, ANY, SOME, ALL

Operator describe
IN Within the specified collection range, select one from more than one
NOT IN Not within the specified collection range
ANY In the list returned by the subquery, any one of them can be satisfied
SOME Same as ANY, ANY can be used wherever SOME is used.
ALL All values ​​in the list returned by the subquery must satisfy

Demo:

 1. Query information about employees whose salary is higher than that of everyone in the finance department

First check the salaries of all finance department personnel

select salary from emp e where e.dept_id = (select id from dept where name = '财务部');

Nest it again

select * from emp e
    where salary >
        all(select salary from emp e where e.dept_id = (select id from dept where name = '财务部'));
-- 相当于 salary > all(8500,48000,5250)

2. Query information about employees whose salary is higher than that of any person in the R&D department

select * from emp
    where salary > any
                    (select salary from emp where dept_id =
                            (select id from dept where name = '研发部'));
-- 这里any也可以使用some,效果是一样的

row subquery

The result returned by a subquery is a row (can be multiple columns). This subquery is called a row subquery .

Commonly used operators: =, <>, IN, NOT IN 

Example demonstration:

Query the information of employees with the same salary and direct leadership as 'Zhang Wuji'

First check the salary and direct leadership of 'Zhang Wuji'

select salary,managerid from emp where name = '张无忌';

 

Then query the information of employees with the same salary and direct leadership as 'Zhang Wuji'

select * from emp where salary = 12500 and managerid = 1;
-- 另一种写法
select * from emp where (salary,managerid) = (12500,1);
-- 行子查询
select * from emp where (salary,managerid) = 
    (select salary,managerid from emp where name = '张无忌');

Table subquery

The result returned by a subquery is multiple rows and multiple columns. This subquery is called a table subquery .

Commonly used operators: IN

Generally placed after from, it can be queried as a temporary new table.

Example demonstration

1. Query employee information with the same position and salary as 'Luzhangke' and 'Song Yuanqiao'

First check the positions and salaries of 'Luzhangke' and 'Song Yuanqiao'

select job,salary from emp where name = '鹿杖客' or '宋远桥';

Perform table subquery again

select * from test.emp where
    (job,salary) in (select job,salary from test.emp where name = '鹿杖客' or '宋远桥');

2. Query the employee information and department information whose joining date is after '2006-01-01'

Also query step by step:

select * from emp where entrydate > '2006-01-01';

 search result:

Then use this as a new table to query. Because all department information needs to be queried, a left join is used here.

select e.*,d.* from (select * from emp where entrydate > '2006-01-01') e
    left join dept d on e.dept_id = d.id;

search result:


end 


Learn from: Dark Horse Programmer - MySQL Database Course

Guess you like

Origin blog.csdn.net/li13437542099/article/details/132481695