【mysql】—— compound query

Foreword:

  • The queries of the mysql table that I have explained before all query one table, which is far from enough in actual development. Therefore, in this issue, I will take you to learn the relevant knowledge about " Compound query"! ! !

Table of contents

(1) Basic query review

 (2) Multi-table query

(3) Self-connection  

(4) Subquery 

1.Single row subquery

2. Multi-row subquery

3. Multi-column subquery

4. Use subqueries in the from clause

5. Merge query

1️⃣ union

2️⃣ union all

(5) OJ practice

(6) Classic test table of oracle 9i

Summarize


(1) Basic query review

Preparation, create an employee information table (classic test table from oracle 9i)

  • EMPPersonnel table
  • DEPTDepartment table
  • SALGRADECapital etc. table

  • 1, Query employees whose salary is higher than 500 or whose position is MANAGER, and their initials must be capital J
select * from emp where (sal>500 or job='MANAGER') and ename like 'J%';

Search shows: 


  •   2. Sort by department number in ascending order and employee salary in descending order.
select * from emp order by deptno, sal desc;

 Search shows: 


  • 3. Sort in descending order using annual salary
select ename, sal*12+ifnull(comm,0) as '年薪' from emp order by 年薪 desc;

 Search shows: 


  •  4. Display the name and job position of the employee with the highest salary
select ename, job from emp where sal = (select max(sal) from emp);

 Search shows: 


  • 5. Display employee information whose salary is higher than the average salary
select ename, sal from emp where sal>(select avg(sal) from emp );

  Search shows: 


  • 6. Display the average salary and maximum salary of each department
select deptno, format(avg(sal), 2) , max(sal) from emp group by deptno;

  Search shows: 


  • 7. Display the department number whose average salary is lower than 2000 and its average salary
select deptno, avg(sal) 平均工资 from emp group by deptno having 平均工资<=2000;

  Search shows: 


  • 8. Display the total number of employees and average salary for each position
select job,count(*) 人数 ,format(avg(sal),2) 平均工资 from emp group by job;

  Search shows: 

The above is a review of the basic query knowledge we learned in the early stage. With the above knowledge, let's officially enter multi-table query!​ 


 (2) Multi-table query

In actual development, data often comes from different tables, so multi-table queries are required. In this section, we use a simple company management system with three tablesEMP, DEPT, SALGRADE to demonstrate how to perform multi-table queries.
  • 1. Display the employee name, employee salary and the name of the department. Because the above data comes from the EMP and DEPT tables, it needs to be queried jointly.

In fact, we only need emp deptno = deptRecords of thedeptno field in the table:
select emp.ename, emp.sal, dept.dname from emp,dept where emp.deptno = dept.deptno;
   Search shows: 


  •  2. Display the department name, employee name and salary of department number 10
select ename, sal,dname from emp, dept where emp.deptno=dept.deptno and dept.deptno=10;

   Search shows: 


  • 3. Display the name, salary, and salary level of each employee  
select ename, sal, grade, losal,hisal from emp,salgrade where emp.sal between losal and hisal;

    Search shows: 


(3)self-contact  

In the database, self-join is a special connection operation,used to join different rows in the same table. Self-join means to connect one column of the table with another column of the table in a table to obtain related data.

Case: Display the superior of employee FORD The number and name of the leader ( mgr is the number of the employee leader --empno )

  • 1. Subquery used:
select empno,ename from emp where emp.empno=(select mgr from emp where ename='FORD');

     Find shows:


  • 2. Use multi-table query (self-query)
select worker.ename,leader.empno from emp leader,emp worker where worker.ename='FORD' and worker.mgr = leader.empno;
-- Use the alias of the table: from emp leader, emp worker. Give your own table an alias. Because the Cartesian product needs to be done first, the alias can be identified first< /span>


(4)子查询 

Subquery: Also known as nested query or inner query, it is a query technology in SQL. Itallows one query to be nested within another query to retrieve more specific or relevant data. Subqueries are often nested within the WHERE clause or FROM clause of the main query to help filter, sort, or join data.

1.单行子查询

A single-row subquery is a subquery thatreturns a single value as a result. The results returned by this kind of query are usually used as conditions for the main query, calculations, or comparisons.

  • Example:Show SMITHEmployees in the same department
select * from emp where deptno = (select deptno from emp where ename='SMITH');

     Find shows:


2、多行子查询

Multi-row subquery is a subquery that returns multiple rows as a result. This type of query is typically used to use these multiple rows of data in the main query for further filtering, comparison, joins, or other operations.

Example

  • in keyword; query the names of employees with the same job position as 10 department, Position, salary, department number, but does not include10yoursyours

     Find shows:


  • all keyword; displays the employees whose salary is higher than the salary of all employees in the department30 Name, salary and department number

The first option: 

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

      Find shows:

The second option: 


  • any keyword; displays employees whose salary is higher than the salary of any employee in department30 Name, salary and department number (including employees in own department)
select ename, sal, deptno from emp where sal > any(select sal from emp where deptno=30);

     Find shows: 


3, Multiple column subquery

A single-row subquery means that the subquery only returns a single column and a single row of data; a multi-row subquery means that a single column and multiple rows of data are returned, both for a single column, and Multiple rows of data are returned. Column subquery refers to a subquery statement that returns data in multiple columns .
  • Case: Query all employees with the same department and position as SMITH, excluding < /span>MyselfSMITH
select ename from emp where (deptno, job)=(select deptno,job from emp where ename='SMITH') and ename <> 'SMITH';

      Find shows: 


4. Use subqueries in the from clause

The subquery statement appears in the from clause. Here we need to use data query skills, using a subquery as a temporary table
Example
  • 1. Display the name, department, salary, and average salary of each employee whose salary is higher than the average salary of his or her department.
 select ename, deptno, sal, format(asal,2) from emp,
     (select avg(sal) asal, deptno dt from emp  group by deptno) tmp
      where emp.sal > tmp.asal and emp.deptno=tmp.dt;


  • 2. Find the name, salary, department, and maximum salary of the person with the highest salary in each department
select emp.ename, emp.sal, emp.deptno, ms from emp,
       (select max(sal) ms, deptno from emp group by deptno) tmp
       where emp.deptno=tmp.deptno and emp.sal=tmp.ms;

 Find shows: 


  • 3. Display the information of each department (department name, number, address) and number of personnel
Method 1 : Usage table
select dept.dname, dept.deptno, dept.loc,count(*) '部门人数' from emp, dept where emp.deptno=dept.deptno group by dept.deptno,dept.dname,dept.loc;

 Find shows: 


Method 2: Use subquery

1. Perform personnel statistics on EMP table

2. Consider the above table as a temporary table
select dept.deptno, dname, mycnt, loc from dept,
    -> (select count(*) mycnt, deptno from emp group by deptno) tmp
    -> where dept.deptno=tmp.deptno;

 Find shows: 


5,joint language

In practical applications, in order to merge the execution results of multiple select, you can use the set operator union, union all

1️⃣ union

The UNION query is used tomerge the result sets of two or more queries and automatically remove duplicate rows. It only returns unique rows.

  • Case: Make the salary greater than2500 or the position is MANAGER Find out
 select ename, sal, job from emp where sal>2500 union
 select ename, sal, job from emp where job='MANAGER';

  Find shows: 


2️⃣ union all

The UNION ALL query is also usedto combine the result sets of two or more queries, but it retains all rows, including duplicate rows .

  • Case: Make the salary greater than25000 or the position is MANAGER Find out
select ename, sal, job from emp where sal>2500 union all
select ename, sal, job from emp where job='MANAGER';

  Find shows:  


(5) OJ practice

After learning the above content, I have given a few OJ exercises for everyone to practice!

Find the salary status of all employees when they join the company

Get the emp_no of all non-manger employees


(6) Classic test table of oracle 9i

DROP database IF EXISTS `scott`;
CREATE database IF NOT EXISTS `scott` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_c    i;

USE `scott`;

 DROP TABLE IF EXISTS `dept`;
 CREATE TABLE `dept` (
   `deptno` int(2) unsigned zerofill NOT NULL COMMENT '部门编号',
   `dname` varchar(14) DEFAULT NULL COMMENT '部门名称',
   `loc` varchar(13) DEFAULT NULL COMMENT '部门所在地点'
 );
 
 
 DROP TABLE IF EXISTS `emp`;
 CREATE TABLE `emp` (
   `empno` int(6) unsigned zerofill NOT NULL COMMENT '雇员编号',
   `ename` varchar(10) DEFAULT NULL COMMENT '雇员姓名',
   `job` varchar(9) DEFAULT NULL COMMENT '雇员职位',
   `mgr` int(4) unsigned zerofill DEFAULT NULL COMMENT '雇员领导编号',
   `hiredate` datetime DEFAULT NULL COMMENT '雇佣时间',
   `sal` decimal(7,2) DEFAULT NULL COMMENT '工资月薪',
   `comm` decimal(7,2) DEFAULT NULL COMMENT '奖金',
   `deptno` int(2) unsigned zerofill DEFAULT NULL COMMENT '部门编号'
 );

 DROP TABLE IF EXISTS `salgrade`;
 CREATE TABLE `salgrade` (
   `grade` int(11) DEFAULT NULL COMMENT '等级',
   `losal` int(11) DEFAULT NULL COMMENT '此等级最低工资',
   `hisal` int(11) DEFAULT NULL COMMENT '此等级最高工资'
 );

 insert into dept (deptno, dname, loc)
 values (10, 'ACCOUNTING', 'NEW YORK');
 insert into dept (deptno, dname, loc)
 values (20, 'RESEARCH', 'DALLAS');
 insert into dept (deptno, dname, loc)                                                  
 values (30, 'SALES', 'CHICAGO');
 insert into dept (deptno, dname, loc)
 values (40, 'OPERATIONS', 'BOSTON');
 
 insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
 values (7369, 'SMITH', 'CLERK', 7902, '1980-12-17', 800, null, 20);
 
 insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
 values (7499, 'ALLEN', 'SALESMAN', 7698, '1981-02-20', 1600, 300, 30);
 
 insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
 values (7521, 'WARD', 'SALESMAN', 7698, '1981-02-22', 1250, 500, 30);

 insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
 values (7566, 'JONES', 'MANAGER', 7839, '1981-04-02', 2975, null, 20);
 
 insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
 values (7654, 'MARTIN', 'SALESMAN', 7698, '1981-09-28', 1250, 1400, 30);

 insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
 values (7698, 'BLAKE', 'MANAGER', 7839, '1981-05-01', 2850, null, 30);

 insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
 values (7782, 'CLARK', 'MANAGER', 7839, '1981-06-09', 2450, null, 10);

 insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
 values (7788, 'SCOTT', 'ANALYST', 7566, '1987-04-19', 3000, null, 20);
 
 insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
 values (7839, 'KING', 'PRESIDENT', null, '1981-11-17', 5000, null, 10);

 insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
 values (7844, 'TURNER', 'SALESMAN', 7698,'1981-09-08', 1500, 0, 30);
 
 insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
 values (7876, 'ADAMS', 'CLERK', 7788, '1987-05-23', 1100, null, 20);
 
 insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
 values (7900, 'JAMES', 'CLERK', 7698, '1981-12-03', 950, null, 30);

 insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
 values (7902, 'FORD', 'ANALYST', 7566, '1981-12-03', 3000, null, 20);
 
 insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
 values (7934, 'MILLER', 'CLERK', 7782, '1982-01-23', 1300, null, 10);
 
 insert into salgrade (grade, losal, hisal) values (1, 700, 1200);
 insert into salgrade (grade, losal, hisal) values (2, 1201, 1400);
 insert into salgrade (grade, losal, hisal) values (3, 1401, 2000);
 insert into salgrade (grade, losal, hisal) values (4, 2001, 3000);
 insert into salgrade (grade, losal, hisal) values (5, 3001, 9999);

Summarize

The above is all about multi-table query in mysql. Thank you everyone for watching and supporting! ! !

Guess you like

Origin blog.csdn.net/m0_56069910/article/details/132846985