MySQL - compound query

Table of contents

MySQL compound query

1. Basic query review

Two, multi-table query

3. Self-connection

4. Sub query

1. Single row subquery

2. Multi-row subqueries

3. Multi-column subquery

4. Using subqueries in the from clause

Five, combined query


MySQL compound query

1. Basic query review

 The query of the mysql table we explained earlier is all about querying a single table, which is far from enough in actual development.

The department table is as follows:

The employee table is as follows:

The salary table is as follows:

Now do the following query:

1.  Query employees whose salary is higher than 500 or whose position is MANAGER , and at the same time, their first letter must be capitalized J

select ename, sal from emp where (sal>500 or job='MANAGER') and ename like 'J%';

 

2. Sort employees in ascending order of department number and descending order of salary

select deptno,sal from emp order by deptno, sal desc;

3. Use annual salary to sort in descending order

select ename, sal*12+ifnull(comm,0) as '年薪' from emp order by 年薪 desc;

4. Display the name and job title of the highest paid employee

select ename, job from EMP where sal = (select max(sal) from EMP);

5. Display information about employees whose salary is higher than the average salary

select ename, sal from emp where sal>(select avg(sal) from emp);

6. Display the average salary and maximum salary for each department

select deptno, avg(sal) 平均工资, max(sal) 最高工资 from emp group by deptno;

7. Display the department number whose average salary is lower than 2000 and its average salary

select deptno, avg(sal) as 平均工资 from emp group by deptno having 平均工资<2000;

8. Display the total number of employees for each position, the average salary

select job,count(*), format(avg(sal),2) from emp group by job;

Two, 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 tables emp, dept, and salgrade to demonstrate how to perform multi-table queries.

  • When performing multi-table query, you only need to put the table names of multiple tables after the from clause and separate them with commas. At this time, MySQL will take the Cartesian product of the given multiple tables as The initial data source for multi-table queries.
  • The essence of multi-table query is to take the Cartesian product of multiple given tables, and then query in the Cartesian product.

        The so-called Cartesian product of multiple tables is to obtain the set of all possible ordered pairs of records in these multiple tables. For example, the following multi-table query is performed on the employee table and department table. Since the query statement does not specify the filter conditions, so the final result is the Cartesian product of the employee table and the department table. (emp has 14 rows of records, dept has 4 rows of records. No row of emp records corresponds to 4 rows of dept records)

        It should be noted that the data obtained after taking the Cartesian product of multiple tables is not all meaningful. For example, when taking the Cartesian product of the employee table and the department table, each employee information in the employee table will be related to the department table. Combining each department information in , and actually an employee is meaningful only when combined with his or her own department information, so it is necessary to filter out the employee’s department number and the department’s number equal record from the Cartesian product (we only need deptno in emp table = record of deptno field in dept table). as follows:

There may be the same column name in multiple tables for Cartesian product. In this case, the column name needs to be specified by means of selection.表名.列名

Display the department name, employee name and salary of department number 10

Since the department name is only available in the department table, and the employee name and employee salary are only available in the employee table, it is necessary to use both the employee table and the department table for multi-table query, and specify the filter condition in the where clause as the employee's department number is equal to Department number, and the record with department number 10. as follows: 

select dname,ename,sal from emp,dept where emp.deptno=dept.deptno and emp.deptno=10;

Display individual employee names, salaries, and pay grades

Since the employee name and salary are only available in the employee table, and the salary level is only available in the salary level table, it is necessary to use the employee table and the salary level table to perform multi-table queries at the same time. In the where clause, specify the filter condition as the employee's salary in Records between losal and hisal. as follows:

select ename,sal,grade from emp,salgrade where sal between losal and hisal;

  • In the Cartesian product of the employee table and the salary grade table, the information of each employee and the information of each salary grade are combined. In fact, it is only meaningful for an employee to combine the salary grade information corresponding to his own salary. of.
  • Therefore, it is necessary to judge whether an employee belongs to the salary level according to the minimum salary and maximum salary of each salary level, and then filter out meaningful records.

3. Self-connection

  • Self-join refers to join query on the same table, that is to say, we can not only take the Cartesian product of different tables, but also take the Cartesian product of the same table.
  • If a field in a table can associate multiple records in the table, then the records associated with the field in the table can be combined through self-join.

Display the number and name of the supervisor of employee FORD 

--使用到表的别名
--from emp worker, emp leader,给自己的表起别名,因为要先做笛卡尔积,所以别名可以先识别
select leader.empno,leader.ename from emp worker,emp leader
where worker.ename='FORD' and worker.mgr=leader.empno;

4. Sub query

  • A subquery is a query statement embedded in other SQL statements, also called a nested query.
  • Subqueries can be divided into single-row subqueries, multi-row subqueries, multi-column subqueries, and subqueries used in the from clause.

1. Single row subquery

A single-row subquery refers to a subquery that returns data in a single row and a single column.

 Show employees in the same department as SMITH

select * from emp where deptno = (select deptno from emp where ename='smith');

2. Multi-row subqueries

A multi-row subquery refers to a subquery that returns multiple rows of single-column data 

in keyword; query the name, position, salary, and department number of the employee who is the same as the job in department 10, but does not include 10's own

select ename, job, sal, deptno from emp
where job in(select distinct job from emp where deptno=10) and deptno!=10;

First check which jobs are available in department No. 10. It is best to deduplicate the results when querying, because some employees in department No. 10 may have the same jobs. as follows:

Then use the above query as a subquery, use the in keyword in the where clause when querying the employee table, and judge that the employee's job position is one of the positions obtained by the subquery. The employee does not include department number 10, so it is also necessary to specify the filter condition in the where clause that the department number is not equal to 10. as follows:

all keyword; displays the name, salary, and department number of employees whose salary is higher than that of all employees in department 30

select ename,sal,deptno from emp where sal > all (select distinct sal from emp where deptno=30);

First query the salaries of employees in department 30. It is best to deduplicate the results when querying, because some employees in department 30 may have the same salary. as follows: 

Then use the above query as a subquery, and use the all keyword in the where clause when querying the employee table to determine whether the salary of the employee is higher than all the salaries obtained by the subquery, and if so, it meets the filter conditions. as follows:

any keyword: display the name, salary and department number of employees whose salary is higher than that of any employee in department 30, including employees in department 30 

 

3. Multi-column subquery

A multi-column subquery refers to a subquery that returns multiple columns of data.

Display employees with the same department and position as SMITH, excluding SMITH himself

select * from emp 
where (deptno, job)=(select deptno,job from emp where ename='SMITH') and ename!='SMITH';

First query the department number of SMITH's department and his position. as follows:

Then use the above query as a subquery. When querying the employee table, in the where clause, specify that the filter condition is that the department number and position are equal to the department number and position obtained by the subquery, and that the employee's name is not SMITH. as follows:

Notice:

  • The result of a multi-column subquery is multi-column data. When comparing multi-column data, the multiple columns to be compared need to be enclosed in parentheses.
  • If the multi-column subquery returns multiple rows of data, you can also use the in, all, and any keywords when filtering data.

4. Using subqueries in the from clause

  • Subqueries can appear not only in the where clause, but also in the from clause.
  • The subquery statement appears in the from clause, and its query result will be used as a temporary table.

Display the name, department, salary, and average salary of each employee whose salary is higher than the average salary of his department 

First query the average salary for each department. as follows: 

Since the displayed information contains the average salary of the department, it is necessary to use the employee table and the above query results to perform multi-table query at the same time. At this time, the above query can be placed in the from clause as a subquery, and then the employee table and the temporary table are retrieved. Calculation, specify in the where clause that the filter condition is that the employee's department number is equal to the department number in the temporary table, and the employee's salary is greater than the average salary in the temporary table. as follows:

Note: When using a subquery in the from clause, an alias must be given to the temporary table obtained by the subquery, otherwise the query will fail.

Displays the name, salary, department, and the department's highest salary of the employee with the highest salary in each department.

First query the maximum salary for each department. as follows:

Put the above query as a subquery in the from clause, then take the Cartesian product of the employee table and the temporary table, and specify in the where clause that the filter condition is that the employee's department number is equal to the department number in the temporary table, and the employee's salary Equal to the highest salary in the temporary table. as follows:

Display the department name, department number, address and number of personnel of each department

Query the number of employees in each department. as follows: 

Put the above query as a subquery in the from clause, then take the Cartesian product of the employee table and the temporary table, and specify in the where clause that the filter condition is that the department number of the employee is equal to the department number in the temporary table. as follows:

In addition, in addition to the above method of subquery + multi-table query, you can also use only multi-table query to solve this problem.

  • First take the Cartesian product of the employee table and the department table.
  • In the where clause, indicate that the filter condition is that the department number of the employee is equal to the number of the department, and filter out meaningful records.
  • In the order by clause, specify grouping by department number, and count the number of people in each department separately.

However, since the title also requires displaying the department name and address of each department, it is necessary to add grouping by department name and address in the group by clause. as follows:

Notice:

  • Because the department name and address are newly added in the select statement, it is necessary to add these two fields in the group by clause, indicating that when the department numbers are the same, group by the department name, and when the department names are the same, continue to follow Addresses are grouped together.
  • However, in the above scenario, the records with the same department number must have the same department name and address. Therefore, in our opinion, it does not make sense to continue adding these two fields in the group by, but the MySQL statement requires us to add them.

Five, combined query

Combined query refers to combining multiple query results, and the operators that can be used are union and union all.

  • Union is used to obtain the union of two query results, and union will automatically remove duplicate rows in the result set.
  • union all is also used to obtain the union of two query results, but union all will not remove duplicate rows in the result set.

 Display employees whose salary is greater than 2500 or whose position is MANAGER

The SQL for querying employees whose salary is greater than 2500 is as follows:

The SQL to query employees whose position is MANAGER is as follows:

To query employees whose salary is greater than 2500 or whose position is MANAGER, you can use the or operator to connect the two conditions in the where clause. as follows:

In the combined query, you can use the union operator to connect the above two query SQLs. At this time, the union of the two query results will be obtained, and the combined results will be deduplicated. as follows:

In addition, you can also use the union all operator to connect the above two query SQLs. At this time, you will also get the union of the two query results, but the combined results will not be deduplicated. as follows:

Notice:

  • The number of columns of the two query results to be merged must be the same, otherwise they cannot be merged.
  • The column attributes corresponding to the two query results to be merged can be different, but this is not recommended.

 

Guess you like

Origin blog.csdn.net/sjsjnsjnn/article/details/129114404