I have an EMPLOYEE table below:
EMP_ID DEPT_ID
101 1
102 2
103 3
104 1
And a DEPARTMENT table as:
DEPT_ID COUNTS
1
2
3
I want to write a query which would count the number of Employee that belong to a department and store it into Department column table so the Department table will look like:
DEPT_ID COUNTS
1 2
2 1
3 1
The solution is
update department p
set counts = (select count(*) from EMPLOYEE e where p.dept_id = e.dept_id);
But i really dont understand how it works internally How does it know which dept ids in DEPARTMENT it has to set counts to. what exactly does this subquery return "select count(*) from EMPLOYEE e where p.dept_id = e.dept_id"
This is called correlated subquery:
This is your query:
update department p
set counts = (select count(*) from EMPLOYEE e where p.dept_id = e.dept_id);
So, the inner query get executed based on the outer query (ie has department
table). If, your outer query has total 3 records then, inner query (ie has EMPLOYEE
table) will get execute three times.
In your scenario, you have mapped the queries with dept_id
from outer query, so this will look up into inner query (ie EMPLOYEE
table) and get the counts based on dept_id
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.