Subqueries of mainstream databases

Article directory

content

Article directory

foreword

4.4 Subqueries

Subqueries Overview

Common operations in subqueries

type of subquery

Subqueries Considerations

subquery expression

Subqueries generate derived tables

Subqueries in WHERE clause

Subquery with in keyword in WHERE clause

Subquery with exists keyword in WHERE clause

Subqueries that restrict comparison operations in the WHERE clause

Insert, update and delete data using subqueries

Modify table data using subqueries

Insert data using subqueries

Updating data with subqueries

Deleting data using subqueries


foreword

Hello everyone, I am the color of ice three points. Personal homepage: blog of ice three colors

This article talks a little bit about subqueries.

Friends passing by, please like and follow before walking. Welcome to the comment area to communicate. It is never too late to start working hard, so it is better to start with this article!

Let's grow together! refill


4.4 Subqueries

Subqueries Overview

Subqueries are SELECT statements nested within other SQL statements, also known as nested queries. A complex query can be decomposed into a series of logical steps through subqueries, and complex query problems can be solved by the combination of single statements.

Query statements containing subqueries can be written in the form of concatenated queries. Therefore, queries between multiple tables can also be implemented through subqueries. In some respects, multi-table joins perform better than subqueries because joins do not require additional operations such as sorting by the query optimizer. Execution of a subquery

The processing process of nested query is from the inner layer to the outer layer. First, the innermost subquery is processed, and then the result of the query is used for the query conditions of the outer query, and then the outer layer is solved, and finally the query result is obtained. .

Common operations in subqueries

Subqueries can include logical operators such as in, not in, any, all, exists, not exists, as well as comparison operators "=", "!=", ">", and "<".

type of subquery

MySQL subqueries can be divided into 4 types according to the results of the subqueries:

A subquery that returns a table is a table subquery

A subquery that returns a row with one or more values ​​is a row subquery

Returns - one or more rows, but with only one value on each row is a column subquery

A scalar subquery that returns only one value. By definition, every scalar subquery is a column subquery and a row subquery.

Subqueries Considerations

1. Subqueries need to be enclosed in parentheses. Subqueries can also contain subqueries, and the nesting can be up to 32 levels.

2. When you need to return a value or a list of values, you can use a subquery instead of an expression. You can also use a subquery to return a result set with multiple columns instead of a table or join to operate the same functionality.

3. Subqueries cannot retrieve columns whose data types are varchar(max), nvarchar(max) and varbinary(max).

4. When sub-query uses order by, it can only be used in the outer layer and cannot be used in the inner layer.

subquery expression

The subquery is used after select, and the result of the subquery can be treated as an ordinary expression.

Example: Query the difference between the salary of No. 7369 employee and the company's average salary

SELECT empno,ename,sal,(SELECT AVG(sal) FROM employee)"average salary",

sal-(SELECT AvG(sal)FROM employee)"salary difference"

FROM employee WHERE empno=7369;

Subqueries generate derived tables

Subqueries are used in the from clause as the derived table data source.

Example: Query the department number, department name, department total number and average salary of each department

SELECT d.deptno,d.dname,e.amount,e.avgsal

FROM department d,

(SELECT deptno,COUNT(*) amount,AVG(sal) avgsal FROM employee GROUP BY deptno) e

WHERE d.deptno=e.deptno;

Subqueries in WHERE clause

The subquery in the where statement actually takes the result of the subquery as part of the condition of the statement, and then uses this condition to filter the data queried at this layer.

Example: Query the information of employees whose salary is higher than the average salary

SELECT empno,ename,sal FROM employee

WHERE sal>(SELECT AVG(sal)FROM employee);

Subquery with in keyword in WHERE clause

When the result column returned by a subquery contains a value, the query requirements apply using comparison operators. If the result set returned by a subquery is a list of values, then the comparison operator can be replaced by the in operator. The in operator can detect whether a specific value exists in the result set, and if the detection succeeds, execute the outer query. not in does the opposite of in.

Example: Query which employees have the highest salary

SELECT empno,ename,job,sal FROM employee

WHERE sal IN(SELECT MAX(sal) FROM employee GROUP BY job);

Subquery with exists keyword in WHERE clause

When using the exists keyword, the inner query statement does not return the queried records, but returns a true or false value. If the inner query statement finds a record that satisfies the condition, it will return a true value (true), otherwise, it will return a false value (false). When the returned value is true, the outer query statement will query; when the returned value is false, the outer query statement will not query or query no records. not exists is the exact opposite of exists.

Example: Query the information of the department with subordinate employees (No. 40 department currently has no employees)

SELECT deptno,dname,loc FROM department d

WHERE EXISTS(SELECT *FROM employee e WHERE d.deptno=e.deptno);

Subqueries that restrict comparison operations in the WHERE clause

The ALL, SOME, and ANY operations are further restrictions on comparison operations.

ALL specifies that the expression should be compared with each value in the subquery result set, and returns true only when the expression and each value satisfy the comparison relationship, otherwise returns false.

SOME or ANY are synonyms, indicating that the expression returns true as long as it satisfies the comparison relationship with a value in the subquery result set, otherwise it returns false.

Example: Query the information of the department with the largest number of people

SELECT deptno,dname,loc

FROM department

WHERE deptno

IN (SELECT deptno FROM employee GROUP BY deptno HAVING COUNT(*)>=ALL(SELECT COUNT(*)FROM employee GROUP BY deptno));

Example: Querying which employees are paid less than the average salary for any position

SELECT empno,ename,job,sal

FROM employee

WHERE sal <ALL(SELECT AVG(sal) FROM employee GROUP BY job);

Example: Query which employees have a salary higher than the average salary of the lowest position

SELECT empno,ename,job,sal

FROM employee

WHERE sal > ANY(SELECT AVG(sal) FROM employee GROUP BY job);

Insert, update and delete data using subqueries

Modify table data using subqueries

It is to use a subquery nested in an insert, update or delete statement to add, update and delete data in the table in batches.

Insert data using subqueries

A select subquery in an insert statement can be used to add values ​​from one or more other tables or views to a table. Use the select subquery to insert multiple rows at the same time.

Updating data with subqueries

A select subquery in an update statement can be used to update the values ​​of one or more other tables or views. Use the select subquery to update multiple rows of data at the same time. Actually by including the result of the subquery as part of the update condition expression.

Deleting data using subqueries

A subquery is used in the delete statement, and the result of the subquery is used as a part of the delete condition expression to delete the data rows that meet the conditions.

Example: Add records of employees who have been hired after 2008-09-01 to the emptest table.

INSERT INTO emptest (

SELECT*FROM employee WHERE hiredate>='2008-09-01');

Check out the emptest table

Note: The select list of the subquery must match the list of insert statement columns. If the insert statement does not specify a list of columns, the select list must match and in the same order as the columns of the table into which it is inserted.

Example: Increase the salary of employees with a department address in DALLAS by 5%.

UPDATE emptest SET sal=sal*1.05

WHERE deptno IN(SELECT deptno FROM department WHERE loc='DALLAS');

Guess you like

Origin blog.csdn.net/qq_46007633/article/details/124048053