SQL - Subqueries

In the SQL language, a SELECT-FROM-WHERE statement is called a query block.

A subquery (or inner query) is a SELECT query that is nested within

(1)  WHERE of SELECT, UPDATE, INSERT, DELETE statements ,

(2) In the HAVING clause with GROUP BY ,

(3) or in other subqueries

 (Together with the comparison (6) or logical (3) operators to form the query condition) The SELECT query of the subquery is always enclosed in parentheses

(Syntactically speaking, a subquery is a special "condition" enclosed in parentheses, which completes a relational operation, so a subquery can appear where expressions are allowed)

1 where nested subqueries

Query information about employees with above-average salaries.

1: Query the average salary first

mysql> select avg(sal) from emp;
+-------------+
| avg(sal)    |
+-------------+
| 2073.214286 |
+-------------+

2: Query higher than average salary

select * from emp 
where sal > (select avg(sal) from emp);

2 from nested subqueries

Query the pay scale for the average salary for each department. 

1: Find the average salary of each department as a temporary table t

mysql> select deptno,avg(sal) as avgsal from emp group by deptno;
+--------+-------------+
| deptno | avgsal      |
+--------+-------------+
|     20 | 2175.000000 |
|     30 | 1566.666667 |
|     10 | 2916.666667 |
+--------+-------------+

2: Connect t table and salgrade table, condition (t.avgsal between s.losal and s.hisal)

select 
    t.*,s.grade
from
    (select deptno,avg(sal) as avgsal from emp group by deptno) t
join
    salgrade s
on
    t.avgsal between s.losal and s.hisal;

3 select nested subqueries

Query the department name of each employee's department, and display the employee name and department name.

depnto corresponding to ename in the emp table, and deptno corresponding to dname in the dept table

select 
    e.ename,(select d.dname from dept d where e.deptno=d.deptno) as dname
from 
    emp e;

Multi-table join query 

select 
    e.ename,d.dname
from
    emp e
join
    dept d
on
    e.deptno=d.deptno;

Example 56: Count the number of courses and average grades of these students who have taken the "VB" course.

SELECT 
    SNO 学号, count(*) 选课门数,AVG(GRADE) 平均成绩          
from 
    sc 
where  
    sno 
in 
    (Select sno from sc join course c On c.cno=sc.cno Where cname='vb')
Group by 
    sno 

Multi-table joins cannot be used (when the query needs to be divided into steps, only subqueries can be used. That is, the query target column comes from a table, but when statistical functions are involved and the conditions come from other tables, use subqueries instead of multi-table joins):

#  (结果错误)
select sno 学号, count(*) 选课门数 , avg(grade) 平均成绩
from
    sc 
join 
    course c 
on
    c.cno=sc.cno
where 
    cname='vb'
group by 
    sno;                           

Guess you like

Origin blog.csdn.net/J__aries/article/details/130161680