MySQL basics (4)-data query language DQL (3) multi-table query

Preface

  Our last article to introduce some table query examples , these examples are Business interview Zhenti, from cattle off network . In fact, MySQL focuses on practice, and the grammar is very fixed, unlike algorithm questions that require a certain idea, but it is enough for MySQL to check the questions, so more practice is needed. This article introduces you to multi-table join query and nested query. First, I will introduce you to multi-table query.

1. Multi-table query

  We have single-table queries and multi-table queries in MySQL. In a multi-table query, multiple tables are connected through key fields with the same meaning in different tables to query field information in different tables. Our connection methods are generallyInner connection and outer connection, Which is the often mentioned left connection and right connection. Generally speaking, the result of multi-table connection is determined by the following three attributes:

  • Directionality : In the outer join, the table written in the front is the left table, and the table written in the back is the right table
  • Primary attachment relationship : the primary table must list all the data ranges. When there is no matching item between the attached table and the primary table, it is marked as null, and there is no main attached table when it is internally connected.
  • Correspondence : the table with repeated values ​​in the key field is multi-table, and the table without repeated values ​​is one table

  In fact, when we are doing a multi-table connection, whether it is a left connection or a right connection, the most important thing is to determine which table is the main table in the multiple tables. If it is a left connection, the main table is in front, and if a right connection is used, It is on the right. When we connect, we are divided into one-to-one, one-to-many and many-to-many modes. The modes are as follows:



  Why do we split the table? In fact, in order to save storage space and avoid data redundancy. If all the data is placed in one table, it is as follows:

  First, we introduce inner joins. Combine the two tables according to the join condition and return the rows that meet the condition. The following select 字段1[,…] from 表1[ inner] join 表2 on 表1.key=表2.key;format: . It is expressed as a set in mathematics as follows:

  the query in the table reflects the following:

  Next, we introduce the left join. In addition to the rows that meet the join conditions, the results also include all rows in the left table. The following select 字段1[,…] from 表1 left join 表2 on 表1.key=表2.key;format: . It is expressed as a set in mathematics as follows:

  the query in the table reflects the following:

  Finally, we introduce the right connection. In addition to the rows that meet the join conditions, the results also include all rows in the right table. The following select 字段1[,…] from 表1 right join 表2 on 表1.key=表2.key;format: . It is expressed as a set in mathematics as follows:

  the query in the table reflects the following: in

  addition to these three queries, we can also query jointly. That is, the query results of multiple select statements are combined into a result set.The number of columns, order, and data type of the result set to be merged must be exactly the same

  union deduplication : select 字段1[,字段2,…] from 表名 union select 字段1[,字段2,…] from 表名;
  union not All weight : select 字段1[,字段2,…] from 表名 union all select 字段1[,字段2,…] from 表名;

  The specific query results are as follows:

Two, multi-table query connection case

  We first create the table t1and t2, the specific commands are as follows:

create table t1(key1 char,v1 int);
create table t2(key2 char,v2 int);

  Secondly, we insert some data into the t1 and t2 tables, and the execution is as follows:

insert into t1 values('a',1),('a',2),('b',3),('c',4),('a',13);                    
insert into t2 values('b',10),('b',11),('a',12),('a',13),('e',14);

  After inserting the data, we check the t1 and t2 tables;

select * from t1;
select * from t2;

  The effect of the executed code is as follows:

  we next connect these two tables; the command is as follows:

select * from t1 inner join t2 on t1.key1 = t2.key2;
select * from t1  join t2 on t1.key1 = t2.key2;

  The results of the execution of the two commands are as follows:

  We next left join the two tables, the command is as follows:

select * from t1 left join t2 on t1.key1 = t2.key2;

  The execution results of the two commands are as follows:

  Next, I will right join the two tables for everyone; the MySQL statement is as follows:

select * from t1 right join t2 on t1.key1 = t2.key2;

  The execution results of the two commands are as follows:

  Finally, the combined query is introduced. The specific statements are as follows:

select * from t1 union select * from t2;

  The command execution result is as follows:

  We found that after the merge, the database is automatically deduplicated. If it is not deduplicated, we can use it union all. The specific implementation is as follows:

select * from t1 union all select * from t2;

  The command execution result is as follows:

  We are giving a few cases of multi-table connection, we first create the salgradetable; the specific statement is as follows:

create table salgrade(grade int,losal int,hisal int);

  Insert the corresponding data as follows:

insert into salgrade values (1,700,1200),(2,1201,1400),(3,1401,2000),(4,2001,3000),(5,3001,9999);

  We look at the salgradetable we just created :

select * from salgrade;

  Command execution results are as follows:

  query each employee ename, dname, sal, because of our investigation are pertinent information about each employee; therefore, our main emp table, where the emp and dept tables we mentioned our previous article have Data, readers of the exercise can read this article . The specific implementation is as follows:

select empname,dname,sal
from emp left join dept on emp.deptno = dept.deptno;

  The command execution result is as follows:

  query the number of employees in each region, the specific implementation code is as follows:

select loc,count(empno) 员工数
from emp left join dept on  emp.deptno = dept.deptno
group by loc;

  Command execution results are as follows:

  query manager's name, department name and date of entry ename, dname, job, hiredate(en / Cartesian product connection), using the following command:

select empname,dname,job,hiredate
from emp inner join dept on emp.deptno=dept.deptno
where job='manager';

  The command execution result is as follows:

  Next, use Cartesian product to achieve:

select empname,dname,job,hiredate
from emp,dept
where emp.deptno=dept.deptno and job='manager';

  Command execution results are as follows:

  query each employee's salary grades; empno, ename, sal, grade(not equijoins), specifically to achieve the following:

select empno,empname,sal,grade
from emp left join salgrade on sal between losal and hisal;

  The command execution result is as follows:

  query the number of employees in each salary grade, the specific realization is as follows:

select grade,count(empno) 员工数
from salgrade left join emp on sal between losal and hisal
group by grade;

  The command execution result is as follows:

  Query the names of all employees and their direct leaders (self-connection: treat the same table as multiple tables through aliases), the specific implementation is as follows:

select e.empname 员工姓名, l.empname 领导姓名
from emp l left join emp e on l.mgr = e.empno;

  Command execution results are as follows:

  query entry date earlier than directly under the leadership of employees: empno, ename, dname, specifically to achieve the following:

select e.empno,e.empname,dname
from emp e 
left join emp l on e.mgr = l.empno 
left join dept on e.deptno = dept.deptno
where e.hiredate < l.hiredate;

  The command execution result is as follows:

Three, subquery

  We introduce subqueries. In fact, subqueries and multi-table joins are similar, and it is not difficult to find from yesterday's exercise : As long as you use multi-table joins, you can use subqueries instead. A subquery is a select statement that contains another or more complete select statements. There are two places where sub-queries appear: they appear in the where clause, that is, the result returned by the sub-query is used as the condition of the main query, and the other is in the from clause, that is, the result returned by the sub-query As a table for the main query. The main categories of subqueries are as follows:

  • Scalar sub query : The returned result is a data (single row and single column)
  • Row subquery : The returned result is one row (single row and multiple columns)
  • Column query : The returned result is one column (multiple rows and single column)
  • Table subquery : The returned result is a temporary table (multiple rows and multiple columns)

  The operators of our subquery are as follows:

Fourth, sub-query case analysis

  Let's first introduce the case of scalar quantum query; query the information of employees whose basic salary is higher than the average salary of the company. The specific implementation of the SQL statement is as follows:

select *
from emp
where sal > (
	select avg(sal) from emp
);

  Command execution results are as follows:

  query and allen with a leading employee: empno, ename, job, mgr, specifically to achieve the following:

select empno,empname,job,mgr
from emp
where mgr=(select mgr from emp where empname = 'allen') and empname <> 'allen';

  The command execution result is as follows:

  Next, we list the cases of sub-queries. Queries department with employees and with the smith positions: empno, ename, job, deptno, specifically to achieve the following:

select empno,empname,job,deptno
from emp 
where (deptno, job) = (select deptno, job from emp where empname = 'smith') and empname <> 'smith';

  The command execution result is as follows:
  In addition, we enumerate examples of Liezi query. Query general staff salary levels: empno, ename, sal, grade, specifically to achieve the following:

select empno,empname,sal,grade
from emp left join salgrade on sal between losal and hisal
where empno not in (select distinct mgr from emp where mgr is not null);

  Command execution results are as follows:

  Query number of employees less than five employees in all departments: empno, ename, deptno: specifically to achieve the following:

select empno,empname,deptno
from emp
where deptno in (select deptno from emp group by deptno having count(empno)>=5);

  The command execution result is as follows:

  query the employee information of any employee whose basic salary is higher than that of department 30, and the specific implementation is as follows:

select * 
from emp
where sal > any(select sal from emp where deptno = 30) and deptno <> 30;

select *
from emp
where sal > (select min(sal) from emp where deptno = 30) and deptno <> 30;

  The command execution result is as follows:

  query the employee information of all employees in the department whose basic salary is higher than 30, the specific implementation is as follows:

select * 
from emp
where sal > all(select sal from emp where deptno = 30) and deptno <> 30;

select *
from emp
where sal > (select max(sal) from emp where deptno = 30) and deptno <> 30;

  Command execution results are as follows:

  Finally, we introduce cases from sub-queries, queries maximum wage of employees of various departments: empno, ename, sal, deptno, specifically to achieve the following:

select empno,empname,sal,emp.deptno
from emp
left join (select deptno,max(sal) 最高工资 from emp group by deptno) t on emp.deptno = t.deptno
where sal = 最高工资;

  The command execution result is as follows:

to sum up

  Our last article to introduce some table query examples , these examples are Business interview Zhenti, from cattle off network . In fact, MySQL focuses on practice, and the grammar is very fixed, unlike algorithm questions that require a certain idea, but it is enough for MySQL to check the questions, so more practice is needed. This article introduces multi-table join queries and nested queries, including inner joins and outer joins, as well as the usage of sub-queries, including keywords such as in and any. Finally, this part is explained through case studies, in order to allow everyone to better apply the knowledge points introduced. Therefore, mysql is a very important skill. Almost every job in the computer needs a mysq skill. Therefore, we need special mastery. Life is endless and struggle is endless. We work hard every day, study hard, constantly improve our abilities, and believe that we will learn something. Come on! ! !

Guess you like

Origin blog.csdn.net/Oliverfly1/article/details/115049542