Subquery: another way to query multiple tables

In the previous article, we introduced how to use JOIN in SQL statements to obtain related data in multiple tables, and specifically discussed the principles of inner joins, left/right/full outer joins, cross joins, natural joins, and self-joins And how to use it.

In addition to join queries, SQL also provides another way to query multiple tables at the same time: Subquery. In this article, we will take a look at various types of subqueries and related operators.

What is a subquery?

Let us first consider a question, which employees have a monthly salary greater than the average monthly salary of all employees? You can first use the AVG function to get the average monthly salary of all employees:

SELECT AVG(salary)
  FROM employee;

AVG(salary)|
-----------|
9832.000000|

Then use the result of the query as the query condition of the following statement to return employees whose monthly salary is greater than 9832:

SELECT emp_name, salary
  FROM employee
 WHERE salary > 9832;

The result of this statement is as follows:

subquery

We used two queries to solve this simple problem, but the requirements in actual applications are often more complicated; obviously we need more advanced query functions.

SQL provides a query method called subquery, which can solve this problem very easily:

SELECT emp_name, salary
  FROM employee
 WHERE salary > (
                 SELECT AVG(salary)
                   FROM employee
                );

Guess you like

Origin blog.csdn.net/horses/article/details/108729099