Table of Contents
Build a database and create a table to insert data
testquestion
The answer is not unique, it is for reference only
Home Database Mysql Tutorial MYSQL complex query method example analysis

MYSQL complex query method example analysis

Jun 03, 2023 am 08:40 AM
mysql

Build a database and create a table to insert data

The code can be copied directly in sequence

-- 建库
CREATE DATABASE `emp`;
-- 打开库
USE emp;
-- 建dept表
CREATE TABLE `dept`( `deptno` INT(2) NOT NULL, `dname` VARCHAR(14), `loc` VARCHAR(13), CONSTRAINT pk_dept PRIMARY KEY(deptno) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- 键emp表
CREATE TABLE `emp` ( `empno` int(4) NOT NULL PRIMARY KEY, `ename` VARCHAR(10), `job` VARCHAR(9), `mgr` int(4), `hiredate` DATE, `sal` float(7,2), `comm` float(7,2), `deptno` int(2), CONSTRAINT fk_deptno FOREIGN KEY(deptno) REFERENCES dept(deptno) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- 建salgrade表
CREATE TABLE `salgrade` ( `grade` int, `losal` int, `hisal` int ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- 插入数据
INSERT INTO dept VALUES (10,'ACCOUNTING','NEW YORK'); 
INSERT INTO dept VALUES (20,'RESEARCH','DALLAS');
INSERT INTO dept VALUES (30,'SALES','CHICAGO'); 
INSERT INTO dept VALUES (40,'OPERATIONS','BOSTON');
INSERT INTO EMP VALUES (7369,'SMITH','CLERK',7902,'1980-12-17',800,NULL,20); 
INSERT INTO EMP VALUES (7499,'ALLEN','SALESMAN',7698,'1981-02-20',1600,300,30); 
INSERT INTO EMP VALUES (7521,'WARD','SALESMAN',7698,'1981-02-22',1250,500,30); 
INSERT INTO EMP VALUES (7566,'JONES','MANAGER',7839,'1981-04-02',2975,NULL,20);
INSERT INTO EMP VALUES (7654,'MARTIN','SALESMAN',7698,'1981-09-28',1250,1400,30); 
INSERT INTO EMP VALUES (7698,'BLAKE','MANAGER',7839,'1981-05-01',2850,NULL,30); 
INSERT INTO EMP VALUES (7782,'CLARK','MANAGER',7839,'1981-06-09',2450,NULL,10); 
INSERT INTO EMP VALUES (7788,'SCOTT','ANALYST',7566,'1987-07-13',3000,NULL,20); 
INSERT INTO EMP VALUES (7839,'KING','PRESIDENT',NULL,'1981-11-07',5000,NULL,10); 
INSERT INTO EMP VALUES(7844,'TURNER','SALESMAN',7698,'1981-09-08',1500,0,30); 
INSERT INTO EMP VALUES (7876,'ADAMS','CLERK',7788,'1987-07-13',1100,NULL,20); 
INSERT INTO EMP VALUES (7900,'JAMES','CLERK',7698,'1981-12-03',950,NULL,30); 
INSERT INTO EMP VALUES (7902,'FORD','ANALYST',7566,'1981-12-03',3000,NULL,20); 
INSERT INTO EMP VALUES (7934,'MILLER','CLERK',7782,'1982-01-23',1300,NULL,10);
INSERT INTO SALGRADE VALUES (1,700,1200); 
INSERT INTO SALGRADE VALUES (2,1201,1400); 
INSERT INTO SALGRADE VALUES (3,1401,2000); 
INSERT INTO SALGRADE VALUES (4,2001,3000); 
INSERT INTO SALGRADE VALUES (5,3001,9999);
Copy after login

dept table:

MYSQL complex query method example analysis

emp table:

MYSQL complex query method example analysis

salgrade table:

MYSQL complex query method example analysis

testquestion

1. List all employees and department names and department headcount who are engaged in the same work as "SCOTT".

2. List the number and average salary of employees in each salary grade of the company.

3. List the names, salaries, and department names of employees whose salaries are higher than the salaries of all employees working in department 30.

4. List the number of employees working in each department, average salary, and average length of service.

5. List the names, department names and salaries of all employees.

6. List all department details and department headcount.

7. List the minimum wages for various jobs and the names of employees who perform the jobs.

8. List the minimum salary, name, department name, and department headcount of MANAGERs in each department.

9. List the annual salary and department name of all employees, sorted by annual salary from low to high.

10. Find out the name of an employee’s superior supervisor and department, and ask for the salary of these supervisors exceeding 3000

11. Find out the department name with ‘S’ The character's department employees, total salary, and department headcount.

12. To increase the salary of employees who have been employed for more than 30 years or were hired in 1987, the salary increase principle is: 10% increase for department 10, 20% increase for department 20, 30% increase for department 30, and so on.

13. List the information of all departments with at least one employee:

14. List all employees whose salary ratio is SMITH:

15. List all employees name and the name of his immediate supervisor:

16. List the number, name, and department name of all employees whose employment date is earlier than that of his or her direct supervisor

17. List the department name and Employee information of these departments, and list those departments without employees

18. List the names of all "CLERK (staff)" and department names, and the number of people in the department

19. List Various jobs with a minimum salary greater than 1,500 and the total number of employees engaged in this job

20. List the names of employees working in the department "SALES", assuming that the department number of the sales department is not known

21. List all employees whose salary is higher than the company’s average salary, their department, superior leader, and company’s salary grade

22. List all department numbers and names with at least one employee, and count these The average salary, minimum salary, and maximum salary of the department.

23. List the numbers, names, department names, and names of their leaders of all employees whose salary is more than "SMITH" or "ALLEN".

24. List the numbers and names of all employees and the numbers and names of their immediate superiors. The displayed results are sorted in descending order of the leader's annual salary.

25. List the number, name, department name, department location, and department headcount of all employees whose employment date is earlier than that of their immediate superiors.

26. List the department names and employee information (number, average salary) of these departments, and also list those departments without employees.

27. List the names of all "CLERK" (clerks) and their department names, number of people in the department, and salary grade.

28. List the various jobs with a minimum salary greater than 1,500 and the number of employees engaged in this job, as well as the name of the department, location, and average salary.

29. List the names, basic salaries, employment dates, and department names of employees working in the department "SALES" (Sales Department). It is assumed that the department number of the Sales Department is not known.

30. List all employees whose salary is higher than the company’s average salary, their departments, superiors, and company salary grades.

31. List all employees and department names and department headcount who perform the same job as "SCOTT".

32. Query the structure of the dept table

33. Retrieve the emp table, use the string is a to connect the two fields of employee name and type of work

34. Retrieve emp The table shows the names, monthly income and commissions of commissioned employees.

The answer is not unique, it is for reference only

It’s a bit messy, the format of pasting it directly is different, let’s make do with it, I can barely see it clearly

– 2. List the number and average salary of employees in each salary grade of the company.

show tables; select * from salgrade; select s.grade,count(),avg(e.sal) from emp e left join salgrade s on e.sal between s.losal and s.hisal group by s.grade ;
Copy after login

3. List the names, salaries and department names of all employees whose salary is higher than that of employees in department 30.

select ename,sal,d.dname,d.deptno from emp e left join dept d on e.deptno = d.deptno where e.sal > (select max(sal) from emp where deptno = 30);
Copy after login

– 4. List the number of employees working in each department, average salary, and average length of service.

select count(),avg(sal),avg(year(now())-year(hiredate)) from emp group by deptno;
Copy after login

– 5. List the names, department names, and salaries of all employees.

SALES research accounting select e.ename,d.dname,e.sal from emp e left join dept d on d.deptno = e.deptno;
Copy after login

– 6. List all department details and department headcount.

OPERATIONS select d.,count(e.ename) from dept d left join emp e on e.deptno = d.deptno group by d.deptno;
Copy after login

– 7. List the minimum wages for various jobs and the names of employees who perform the jobs.

select a.ename,t. from emp a left join (select e.job,min(e.sal) from emp e group by e.job) t on a.job = t.job;
Copy after login

– 8. List the minimum salary, name, department name, and department headcount of the MANAGER in each department.

– binary 实现区分大小写 – select ename from emp where job = binary ‘MANAGER'; – select binary ‘a' = ‘a'; – select binary ‘a'; – select binary ‘A'; select * from emp where job = binary ‘MANAGER'; select a.mm,c.ename,c.job,b.dname,b.cc from (select d.deptno,min(sal) mm from emp e left join dept d on e.deptno = d.deptno where job = ‘MANAGER' group by deptno) a left join (select d.deptno,d.dname,count() cc from emp e left join dept d on e.deptno = d.deptno group by d.deptno) b on a.deptno = b.deptno left join emp c on c.sal = a.mm and b.deptno = c.deptno ;
Copy after login

– 9. 列出所有员工的年工资,所在部门名称,按年薪从低到高排序。

select empno,ename,sal12,d.dname from emp left join dept d on d.deptno = emp.deptno order by sal12 asc;
Copy after login

– 10. 查出某个员工的上级主管及所在部门名称,并要求出这些主管中的薪水超过3000

select a.empno,a.ename,b.ename,b.sal from emp a left join emp b on a.mgr = b.empno where b.sal>3000 and a.empno = 7566; select a.empno,a.ename,b.ename,b.sal from emp a left join emp b on a.mgr = b.empno where b.sal>3000; select a.empno,a.ename,b.ename,b.sal from emp a left join emp b on a.mgr = b.empno;
Copy after login

– 11. 求出部门名称中,带‘S’字符的部门员工的、工资合计、部门人数。

select d.dname,count(),sum(e.sal) from emp e left join dept d on e.deptno = d.deptno where d.dname like ‘%s%' group by d.deptno; select * from emp;
Copy after login

– 12. 给任职日期超过30年或者在87年雇佣的雇员加薪,加薪原则:10部门增长10%,20部门增长 20%,30部门增长30%,依次类推。

select empno,ename,sal,sal+sal*(deptno/100) from emp where year(curdate()) - year(hiredate)>30 or year(hiredate)=2022; update emp set sal = sal+sal*(deptno/100) where year(curdate()) - year(hiredate)>30 or year(hiredate)=2022; select * from emp;
Copy after login

– 13. 列出至少有一个员工的所有部门的信息

select distinct d.* from dept d join emp e on d.deptno = e.deptno;
Copy after login

– 14. 列出薪金比SMITH低的所有员工

select * from emp where sal < (select sal from emp where ename = ‘SMITH&#39;)
Copy after login

– 15. 列出所有员工的姓名以及其直接上级的姓名:

select a.empno,a.ename,b.ename from emp a left join emp b on a.mgr = b.empno;
Copy after login

– 16. 列出受雇日期早于其直接上级的所有员工的编号、姓名,部门名称

select a.empno,a.ename,b.ename,d.dname from emp a left join emp b on a.mgr = b.empno and a.hiredate<b.hiredate left join dept d on d.deptno = a.deptno;
Copy after login
Copy after login

– 17. 列出部门名称和这些部门的员工信息,同时列出那些没有员工的部门

select * from dept d left join emp e on d.deptno = e.deptno;
Copy after login

– 18. 列出所有"CLERK(职员)"的姓名以及部门名称,部门的人数

select a.ename,a.job,b.dname,b.cc from emp a join (select d.deptno,d.dname,count() cc from dept d left join emp e on d.deptno = e.deptno group by d.deptno) b on b.deptno = a.deptno and a.job = ‘CLERK&#39;;
Copy after login

– 19. 列出最低薪金大于1500的各种工作以及从事此工作的全部雇员人数

select job,max(sal),min(sal),avg(sal),count() from emp where sal>1500 group by job;
Copy after login
Copy after login

– 20. 列出在部门"SALES"工作的员工的姓名,假定不知道销售部的部门编号

select ename from emp where deptno in (select deptno from dept where dname=‘sales&#39;); select e.ename from emp e join dept d on e.deptno = d.deptno and d.dname=‘sales&#39;;
Copy after login

– 21. 列出薪金高于公司平均薪金的所有员工,所在部门,上级领导,公司的工资等级

select a.ename,a.en,d.dname,a.sal,s.grade from (select a.deptno,a.ename,b.ename en,a.sal from emp a join emp b on a.mgr = b.empno and a.sal>(select avg(sal) from emp)) a left join dept d on a.deptno=d.deptno left join salgrade s on a.sal between s.losal and s.hisal; select a.ename,b.ename from emp a join emp b on a.mgr = b.empno and a.sal> (select avg(sal) from emp);
Copy after login

– 22. 列出至少有一个员工的所有部门编号、名称,并统计出这些部门的平均工资、最低工资、最高 工资。

select e.deptno,d.dname,avg(e.sal),max(e.sal),min(sal),count() from dept d join emp e on e.deptno = d.deptno group by e.deptno;
Copy after login

– 23. 列出薪金比“SMITH”或“ALLEN”多的所有员工的编号、姓名、部门名称、其领导姓名。

select a.empno,a.ename,d.dname,b.ename from (select * from emp where sal >(select min(sal) from emp where ename in (‘smith&#39;,‘allen&#39;))) a left join emp b on a.mgr = b.empno left join dept d on d.deptno = a.deptno;
Copy after login

– 24. 列出所有员工的编号、姓名及其直接上级的编号、姓名,显示的结果按领导年工资的降序排 列。

select a.empno,a.ename,a.sal12,b.empno,b.ename,b.sal12 from emp a left join emp b on a.mgr = b.empno order by b.sal12;
Copy after login

– 25. 列出受雇日期早于其直接上级的所有员工的编号、姓名、部门名称、部门位置、部门人数。

select a.empno,a.ename,b.ename,d.dname from emp a left join emp b on a.mgr = b.empno and a.hiredate<b.hiredate left join dept d on d.deptno = a.deptno;
Copy after login
Copy after login

– 26. 列出部门名称和这些部门的员工信息(数量、平均工资),同时列出那些没有员工的部门。

select d.deptno,d.dname,count(e.ename),avg(sal) from dept d left join emp e on d.deptno = e.deptno group by d.deptno;
Copy after login

– 27. 列出所有“CLERK”(办事员)的姓名及其部门名称,部门的人数,工资等级。

select a.ename,a.job,b.dname,b.cc from emp a join (select d.deptno,d.dname,count() cc from dept d left join emp e on d.deptno = e.deptno group by d.deptno) b on b.deptno = a.deptno and a.job = ‘CLERK&#39;; select e.deptno,count(e.deptno) from (select a.deptno,a.ename,d.dname,s.grade from (select deptno,ename,sal from emp where job=‘CLERK') a left join dept d on a.deptno=d.deptno left join salgrade s on a.sal between s.losal and s.hisal) aa left join emp e on aa.deptno = e.deptno group by e.deptno; select t1.,t2.deptcount from (select d.deptno,e.ename,e.job,d.dname,s.grade from emp e join dept d on e.deptno = d.deptno join salgrade s on e.sal between s.losal and s.hisal where e.job = ‘CLERK') t1 join (select deptno, count() as deptcount from emp group by deptno) t2 on t1.deptno = t2.deptno;
Copy after login

– 28. 列出最低薪金大于1500的各种工作及此从事此工作的全部雇员人数及所在部门名称、位置、 平均工资。

select job,max(sal),min(sal),avg(sal),count() from emp where sal>1500 group by job;
Copy after login
Copy after login

– 29. 列出在部门“SALES”(销售部)工作的员工的姓名、基本工资、雇佣日期、部门名称,假定 不知道销售部的部门编号。

select e.ename,e.sal,e.hiredate,d.dname from emp e join dept d on d.deptno = e.deptno and d.dname=‘sales&#39;;
Copy after login

– 30. 列出薪金高于公司平均薪金的所有员工,所在部门,上级领导,公司的工资等级。

select a.ename,a.en,d.dname,a.sal,s.grade from (select a.deptno,a.ename,b.ename en,a.sal from emp a join emp b on a.mgr = b.empno and a.sal>(select avg(sal) from emp)) a left join dept d on a.deptno=d.deptno left join salgrade s on a.sal between s.losal and s.hisal;
Copy after login

– 31. 列出与“SCOTT”从事相同工作的所有员工及部门名称,部门人数。

create view v1 as select b.ename,d.dname,a.cc from (select deptno,count(*) cc from emp group by deptno) a join (select ename,deptno from emp where job = (select job from emp where ename = ‘scott&#39;)) b on b.deptno=a.deptno
left join dept d on d.deptno = b.deptno; select * from v1;
Copy after login

– 32. 查询dept表的结构

desc emp; describe emp; show create table emp; show columns from emp;
Copy after login

– 33. 检索emp表,用is a 这个字符串来连接员工姓名和工种两个字段 is a 是oracle数据库

select concat(empno,ename,job) from emp; select concat_ws(‘-&#39;,empno,ename,job) from emp; select distinct job from emp; select group_concat(distinct job) from emp; select group_concat(distinct ename) from emp; select group_concat(distinct job order by job asc separator ‘=&#39;) from emp;
Copy after login

– 34. 检索emp表中有提成的员工姓名、月收入及提成。

select ename,sal,comm from emp where comm is not null; select ename,sal,comm from emp where comm is not null and comm>0;
Copy after login

The above is the detailed content of MYSQL complex query method example analysis. 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)

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

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

How to view sql database error How to view sql database error Apr 10, 2025 pm 12:09 PM

The methods for viewing SQL database errors are: 1. View error messages directly; 2. Use SHOW ERRORS and SHOW WARNINGS commands; 3. Access the error log; 4. Use error codes to find the cause of the error; 5. Check the database connection and query syntax; 6. Use debugging tools.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

See all articles