当前位置:网站首页>MySQL learning child query

MySQL learning child query

2022-06-10 23:36:00 Xiao Wang who likes breakfast

# The first 09 Chapter _ Subquery 

#1. The subquery is introduced by a concrete example 
# demand : Whose pay ratio is Abel The height of 
# The way 1:
SELECT last_name,salary
FROM employees
WHERE last_name='Abel';

SELECT last_name,salary
FROM employees
WHERE salary>11000;

# The way 2: Self join 
SELECT e2.last_name,e2.salary
FROM employees e1,employees e2
WHERE e2.`salary`>e1.`salary` # Connection conditions of multiple tables 
AND e1.`last_name`='Abel';

# The way 3: Subquery 
SELECT last_name,salary
FROM employees
WHERE salary>(
	SELECT salary   # The result here should be a column 	
	FROM employees
	WHERE last_name='Abel'
	);
#2. The standard of appellation : External query ( Or main query )、 Internal query ( Or subquery )
/*
 Subquery ( Internal query ) Execute once before the main query .
 The results of the sub query are by the main query ( External query ) Use  .
 matters needing attention 
 Subqueries should be enclosed in parentheses 
 Place the subquery to the right of the comparison criteria 
 Single line operators correspond to single line subqueries , Multiline operators correspond to multiline subqueries 
*/
#3. Classification of subqueries 
/*
 angle 1: The number of item trees returned from the internal query 
	 Single line sub query   vs   Multi line sub query 
 angle 2: Whether the internal query is executed more than once 
	 Correlation subquery   vs   Uncorrelated subqueries 
 such as : Correlation subquery : Query employee information whose salary is greater than the average salary of the Department 
       Uncorrelated subqueries : Query the information of employees whose salary is greater than the average salary of the company 

*/

#4. Single line sub query  
#4.1 Single line operators :=  != > >=  < <=  

# subject : Query salary greater than 149 Information of the employee whose salary is No 
# Writing skills of sub query ( step ):① Write from the inside out  ② Write from the outside to the inside 

SELECT last_name,salary
FROM employees
WHERE salary >(
	      SELECT salary
	      FROM employees
	      WHERE employee_id =149
);

# subject : return job_id And 141 Same as employee No ,salary Than 143 The name of the employee with a large number of employees ,job_id And wages 
SELECT last_name,job_id,salary
FROM employees
WHERE salary>(
	    SELECT salary
	    FROM employees
	    WHERE employee_id=143


)AND job_id=(
	    SELECT job_id
	    FROM employees
	    WHERE employee_id=141

);

# subject : Return to the lowest paid employees of the company last_name,job_id and salary

SELECT last_name,job_id,salary
FROM employees
WHERE salary=( 
		SELECT MIN(salary)
		FROM employees
);

# subject : Query and 141 Of employee No manager_id and department_id same 
#       Other employees employee_id,manager_id,department_id

# The way 1:
SELECT employee_id,manager_id,department_id
FROM employees
WHERE manager_id=(
		SELECT manager_id
		FROM employees
		WHERE employee_id=141
) AND department_id=(
		SELECT department_id
		FROM employees
		WHERE employee_id=141
)AND employee_id<>141;
# The way 2: understand 
SELECT employee_id,manager_id,department_id
FROM employees
WHERE (manager_id,department_id)=(
				SELECT manager_id,department_id
				FROM employees
				WHERE employee_id=141
)AND employee_id<>141;

# subject : The minimum wage is greater than 50 The Department of minimum wage id And its minimum wage 
SELECT department_id,MIN(salary)
FROM employees
WHERE department_id IS NOT NULL
GROUP BY department_id
HAVING  MIN(salary)>(
		SELECT MIN(salary)
		FROM employees
		WHERE department_id=50
);

# subject : Explicit employee employee_id,last_name and location.
#	 among , If employee department_id And location_id by 1800
#	 Of department_id identical , be location by ’Canada’, The rest are ’USA’.
SELECT employee_id,last_name,(CASE department_id WHEN(
								SELECT department_id
								FROM departments
								WHERE location_id=1800

) 							  THEN 'Canada'
							  ELSE 'USA' END) "location"
FROM employees;

#4.2  Null value problem in subquery 
SELECT last_name, job_id
FROM employees
WHERE job_id =
(SELECT job_id
FROM employees
WHERE last_name = 'Haas');

#4.3 Illegal use of subquery 
# error :Subquery returns more than 1 row
SELECT employee_id, last_name
FROM employees
WHERE salary =
		(SELECT MIN(salary)
		FROM employees
		GROUP BY department_id);
#5. Multi line sub query 
#5.1 Operator of multi row subquery :IN ANY ALL SOME( Same as ANY)

#5.2 give an example :
#IN:
SELECT employee_id, last_name
FROM employees
WHERE salary IN
		(SELECT MIN(salary)
		FROM employees
		GROUP BY department_id);		
#ANY/ALL : subject : Return to other job_id Middle ratio job_id by ‘IT_PROG’ Employee number of any low paid employee in the Department 、 full name 、job_id  as well as salary
SELECT employee_id,last_name,job_id,salary
FROM employees
WHERE job_id<>'IT_PROG' 
AND salary< ANY(
	SELECT salary
	FROM employees
	WHERE job_id='IT_PROG'
);
# subject : Return to other job_id Middle ratio job_id by ‘IT_PROG’ Employee number of all low paid employees in the Department 、 full name 、job_id  as well as salary
SELECT employee_id,last_name,job_id,salary
FROM employees
WHERE job_id<>'IT_PROG' 
AND salary< ALL(
	SELECT salary
	FROM employees
	WHERE job_id='IT_PROG'
);
# subject : Query the Department with the lowest average wage id
#MySQL Aggregate functions in cannot be nested ,
# resolvent : Think of the result as a table ,avg_sal As one of the column names , You can query by aliasing the new table 
# The way 1:
SELECT department_id
FROM employees
GROUP BY department_id
HAVING AVG(salary)=(
SELECT MIN(avg_sal)
FROM(
	SELECT AVG(salary) avg_sal
	FROM employees
	GROUP BY department_id
	) t_det_avg_sal

);
# The way 2:
SELECT department_id
FROM employees
GROUP BY department_id
HAVING AVG(salary)<= ALL(
	SELECT AVG(salary) avg_sal
	FROM employees
	GROUP BY department_id
);
#5.3 The null problem 
SELECT last_name
FROM employees
WHERE employee_id NOT IN (
		SELECT manager_id
		FROM employees
		#swhere manager_id is not null
);
#6. Correlation subquery 
#6.1
# subject : Query the salary of employees whose salary is greater than the average salary of the Department last_name,salary And its department_id
# The way 1: Use related subqueries 
SELECT last_name,salary,department_id
FROM employees e1
WHERE salary>(
	      SELECT AVG(salary)
	      FROM employees e2
	      WHERE department_id=e1.`department_id`
);
# The way 2: stay FROM Use subqueries in 
SELECT e.last_name,e.salary,e.department_id
FROM employees e,(
	SELECT department_id,AVG(salary) avg_sal
	FROM employees
	GROUP BY department_id) t_dept_avg_sal
WHERE e.`department_id`=t_dept_avg_sal.`department_id`
AND e.`salary`>t_dept_avg_sal.avg_sal
# subject : Check the employee's id,salary, according to department_name  Sort 
SELECT employee_id,salary
FROM employees e
ORDER BY (
	SELECT department_name
	FROM departments d
	WHERE e.`department_id`=d.`department_id`
)
# Conclusion : stay SLECT In structure , except GROUP BY  and LIMIT outside , Other locations can be queried by the voice 
/*
SELECT  ...,...,...( There are aggregate functions )
FROM ...(LEFT/RIGHT)JOIN...ON Multi table connection conditions 
JOIN...ON...
WHERE  Connection conditions of multiple tables  AND  Filter conditions that do not contain aggregate functions 
GROUP BY ...,...
HAVING  Filter conditions containing aggregate functions 
ORDER BY ...,...(ASC,DESC)
LIMIT ...,...
*/
# subject : if employees In the table employee_id And job_history In the table employee_id The same number is not less than 2,
#	 Output these same id Of our employees employee_id,last_name And its job_id		
SELECT employee_id,last_name,job_id
FROM employees e
WHERE 2<=(
	  SELECT COUNT(*)
	  FROM job_history j
	  WHERE e.`employee_id`=j.`employee_id`
);
#6.2 EXISTS  And  NOT EXISTS keyword 
# subject : Query company managers employee_id,last_name,job_id,department_id Information 
# The way 1: Use self connect 
SELECT DISTINCT mgr.employee_id,mgr.last_name,mgr.job_id,mgr.department_id
FROM employees emp JOIN employees mgr
ON emp.`manager_id`=mgr.`employee_id`;
# The way 2: Subquery 
SELECT 	employee_id,last_name,job_id,department_id
FROM employees
WHERE department_id IN(
			SELECT  DISTINCT manager_id
			FROM employees
			
);
# The way 3: Use EXISTS
SELECT 	employee_id,last_name,job_id,department_id
FROM employees e1
WHERE EXISTS (
		SELECT *
		FROM employees e2
		WHERE e1.`employee_id`=e2.`manager_id`
	);
	
# subject : Inquire about departments In the table , There is no in employees Of the departments in the table department_id and department_name
# The way 1: Use left outer connection 
SELECT d.department_id,d.department_name
FROM departments d LEFT JOIN employees e
ON d.`department_id`=e.`department_id`
WHERE e.`department_id` IS NULL;
# The way 2:
SELECT department_id,department_name
FROM departments d
WHERE NOT EXISTS(
		SELECT *
		FROM employees e
		WHERE d.`department_id`=e.`department_id`
);
# After class questions 
#1. Query and Zlotkey Name and salary of employees in the same department 
SELECT last_name,salary
FROM employees
WHERE department_id IN (
		    SELECT department_id
		    FROM employees
		    WHERE last_name='Zlotkey'
);
#2. Query the employee number of the employee whose salary is higher than the average salary of the company , Name and salary .
SELECT employee_id,last_name,salary
FROM employees
WHERE salary >(
		SELECT AVG(salary)
		FROM employees
);
#3. Select salary greater than all JOB_ID = 'SA_MAN' The salary of the employee last_name, job_id, salary
SELECT last_name,job_id,salary
FROM employees
WHERE salary>ALL(
		SELECT salary
		FROM employees
		WHERE job_id='SA_MAN'
);
#4. Queries and names contain letters u Employee number and name of employees in the same department 
SELECT employee_id,last_name
FROM employees
WHERE department_id IN (
			SELECT DISTINCT department_id
			FROM employees
			WHERE last_name LIKE '%u%'
);
#5. Check the... In the Department location_id by 1700 The employee number of the employee working in the Department 
SELECT employee_id
FROM employees
WHERE department_id IN( 
			  SELECT department_id
			  FROM departments
			  WHERE location_id=1700

);
#6. The query manager is King The name and salary of the employee 
SELECT last_name,salary,manager_id
FROM employees
WHERE manager_id IN (
		    SELECT employee_id
		    FROM employees
		    WHERE last_name='King'
);
#7. Query the lowest paid employee information : last_name, salary
SELECT last_name,salary
FROM employees
WHERE salary=(
		SELECT MIN(salary)
		FROM employees
);
#8. Search the Department with the lowest average wage 
SELECT *
FROM departments
WHERE department_id=(
		SELECT department_id
		FROM employees
		GROUP BY department_id
		HAVING AVG(salary)=(
				SELECT MIN(sal_avg)
				FROM (
					SELECT AVG(salary) sal_avg
					FROM employees
					GROUP BY department_id
				) t_avg_sal


		)

);
# The way 2:
SELECT *
FROM departments
WHERE department_id=(
		SELECT department_id
		FROM employees
		GROUP BY department_id
		HAVING AVG(salary)<= ALL(
					SELECT AVG(salary) sal_avg
					FROM employees
					GROUP BY department_id
		)

);

# The way 3:LIMIT
SELECT d.* 
FROM departments d,(
SELECT department_id,AVG(salary) avg_sal
FROM employees
GROUP BY department_id
ORDER BY avg_sal ASC
LIMIT 0,1
) t_avg_sal
WHERE d.`department_id`=t_avg_sal.`department_id`


#9. Query the information of the Department with the lowest average wage and the average wage of the Department ( Correlation subquery )
SELECT d.*,(SELECT AVG(salary)
	    FROM employees
	    WHERE department_id=d.`department_id`
) avg_sal
FROM departments d
WHERE department_id=(
		SELECT department_id
		FROM employees
		GROUP BY department_id
		HAVING AVG(salary)=(
				SELECT MIN(sal_avg)
				FROM (
					SELECT AVG(salary) sal_avg
					FROM employees
					GROUP BY department_id
				) t_avg_sal


		)

);
#10. Find the highest average wage  job  Information 
# The way 1:
SELECT *
FROM jobs
WHERE job_id=(
	SELECT job_id
	FROM employees
	GROUP BY job_id
	HAVING AVG(salary)=(
		SELECT MAX(avg_sal)
		FROM (
			SELECT AVG(salary) avg_sal
			FROM employees
			GROUP BY job_id
		) t_avg_sal

	)

);
# The way 2:
SELECT *
FROM jobs
WHERE job_id=(
	SELECT job_id
	FROM employees
	GROUP BY job_id
	HAVING AVG(salary)>= ALL(
			SELECT AVG(salary) avg_sal
			FROM employees
			GROUP BY job_id
	)

);
# The way 3:
SELECT *
FROM jobs
WHERE job_id=(
	SELECT job_id
	FROM employees
	GROUP BY job_id
	HAVING AVG(salary)=(
			SELECT AVG(salary) avg_sal
			FROM employees
			GROUP BY job_id
			ORDER BY avg_sal DESC
			LIMIT 0,1
			
	)

);

# The way 4:
SELECT j.*
FROM jobs j,(
SELECT job_id,AVG(salary) avg_sal
FROM employees
GROUP BY job_id
ORDER BY avg_sal DESC
LIMIT 0,1) t_max_sal
WHERE j.`job_id`=t_max_sal.`job_id`;

#11. Query the departments whose average salary is higher than the average salary of the company ?
SELECT department_id
FROM employees
WHERE department_id IS NOT NULL
GROUP BY department_id
HAVING AVG(salary)>
(     SELECT AVG(salary)
      FROM employees
)
#12. Find out all the  manager  Details of 
# The way 1:
SELECT employee_id,last_name,salary
FROM employees
WHERE employee_id IN (
SELECT DISTINCT manager_id
FROM employees
);
# The way 2:
SELECT DISTINCT e1.employee_id, e1.last_name, e1.salary
FROM employees e1 JOIN employees e2
WHERE e1.employee_id = e2.manager_id;
# The way 3:
SELECT employee_id, last_name, salary
FROM employees e1
WHERE EXISTS ( SELECT *
FROM employees e2
WHERE e2.manager_id = e1.employee_id);
#13. In all departments   The Department with the lowest of the highest wages   What's the minimum wage ?
# The way 1:
SELECT MIN(salary)
FROM employees
WHERE  department_id=(
		SELECT department_id
		FROM employees
		GROUP BY department_id
		HAVING MAX(salary)=(
				SELECT MIN(max_sal)
				FROM(
				SELECT department_id,MAX(salary) max_sal
				FROM employees
				GROUP BY department_id
				) t_max_sal

		)


);

# The way 2:
SELECT MIN(salary)
FROM employees
WHERE  department_id=(
		SELECT department_id
		FROM employees
		GROUP BY department_id
		HAVING MAX(salary)<=ALL(
				SELECT MAX(salary) max_sal
				FROM employees
				GROUP BY department_id
				HAVING department_id IS NOT NULL
		)
);

# The way 3:
SELECT MIN(salary)
FROM employees
WHERE  department_id=(
		SELECT department_id
		FROM employees
		GROUP BY department_id
		HAVING MAX(salary)=(
				SELECT MAX(salary) max_sal
				FROM employees
				GROUP BY department_id
				ORDER BY max_sal ASC
				LIMIT 0,1
		)
);
# The way 4:
SELECT MIN(salary)
FROM employees e,(
				SELECT department_id,MAX(salary) max_sal
				FROM employees
				GROUP BY department_id
				ORDER BY max_sal ASC
				LIMIT 0,1) t_max_sal
WHERE e.`department_id`= t_max_sal.`department_id`;
#14. Check the Department with the highest average wage  manager  Details of : last_name, department_id, email, salary
# The way 1:
SELECT last_name, department_id, email, salary
FROM employees
WHERE employee_id IN(
	SELECT DISTINCT manager_id
	FROM employees
	WHERE department_id=(
		SELECT department_id
		FROM employees
		GROUP BY department_id
		HAVING AVG(salary)=(
			SELECT MAX(avg_sal)
			FROM(
			SELECT AVG(salary) avg_sal
			FROM employees
			GROUP BY department_id
			) t_avg_sal

		)
	)

);

# The way 2:
SELECT last_name, department_id, email, salary
FROM employees
WHERE employee_id IN(
	SELECT DISTINCT manager_id
	FROM employees
	WHERE department_id=(
		SELECT department_id
		FROM employees
		GROUP BY department_id
		HAVING AVG(salary)>= ALL(
			SELECT AVG(salary) 
			FROM employees
			GROUP BY department_id
		)
	)

);
# The way 3:
SELECT last_name, department_id, email, salary
FROM employees
WHERE employee_id IN(
SELECT DISTINCT manager_id 
FROM employees e,(
SELECT department_id,AVG(salary) avg_sal
FROM employees
GROUP BY department_id
ORDER BY avg_sal DESC
LIMIT 0,1) t_avg_sal
WHERE e.`department_id`=t_avg_sal.`department_id`);
#15.  Query the department number of the Department , It does not include job_id yes "ST_CLERK" Your department number 
# The way 1:
SELECT department_id
FROM departments
WHERE department_id NOT IN(
		SELECT DISTINCT department_id
		FROM employees
		WHERE job_id='ST_CLERK'

);
# The way 2:
SELECT department_id
FROM departments d
WHERE NOT EXISTS (
		SELECT *
		FROM employees e
		WHERE e.`department_id`=d.`department_id`
		AND e.`job_id`='ST_CLERK'

	);

#16.  Select all employees without managers last_name
SELECT last_name
FROM employees emp
WHERE NOT EXISTS(
	SELECT *
	FROM employees mgr
	WHERE emp.`manager_id`=mgr.`employee_id`
);
#17. Check the employee number 、 full name 、 Employment time 、 Wages , The manager of the employee is  'De Haan'
# The way 1:
SELECT employee_id,last_name,hire_date,salary
FROM employees
WHERE manager_id IN(
		SELECT employee_id
		FROM employees
		WHERE last_name='De Haan'
);

# The way 2:
SELECT employee_id,last_name,hire_date,salary
FROM employees emp
WHERE EXISTS(
	    SELECT *
	    FROM employees mgr
	    WHERE emp.`manager_id`=mgr.`employee_id`
	    AND mgr.`last_name`='De Haan'
);
#18. Query the employee number of employees in each department whose salary is higher than the average salary of the Department ,  Name and salary ( Correlation subquery )
# Mode one : Correlation subquery 
SELECT employee_id,last_name,salary
FROM employees e1
WHERE salary > (
#  Query the average of an employee's department 
SELECT AVG(salary)
FROM employees e2
WHERE e2.department_id = e1.`department_id`
);
# Mode two :
SELECT employee_id,last_name,salary
FROM employees e1,
(SELECT department_id,AVG(salary) avg_sal
FROM employees e2 GROUP BY department_id
) dept_avg_sal
WHERE e1.`department_id` = dept_avg_sal.department_id
AND e1.`salary` > dept_avg_sal.avg_sal;
#19. Query the number of departments under each department is greater than  5  Department name of ( Correlation subquery )
SELECT department_name
FROM departments d
WHERE 5<(
	SELECT COUNT(*)
	FROM employees e
	WHERE d.`department_id`=e.`department_id`
);
#20. The number of departments in each country is greater than  2  Country number of ( Correlation subquery )
SELECT country_id
FROM locations l
WHERE 2<(
	SELECT COUNT(*)
	FROM departments d
	WHERE l.`location_id`=d.`location_id`
);
 /*
	 Writing skills of sub query ( Or steps ):① Write from the inside out  ② Write from the outside to the inside 
	 How to choose ?
	① If the subquery is simpler , It is suggested to write from the outside to the inside , If more complex , Write from the inside out 
	② If it is a related subquery , It is usually written from the outside to the inside 
 */

原网站

版权声明
本文为[Xiao Wang who likes breakfast]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206102220175525.html