简体   繁体   English

在Oracle中使用子查询更新列

[英]Update a column using Subquery in oracle

I have an EMPLOYEE table below: 我下面有一个EMPLOYEE表:

EMP_ID     DEPT_ID
101        1
102        2
103        3
104        1

And a DEPARTMENT table as: 和一个DEPARTMENT表为:

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: 我想编写一个查询,该查询将计算属于某个部门的Employee的数量并将其存储到Department列表中,因此Department表将如下所示:

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. 但是我真的不明白它是如何在内部工作的。它如何知道它必须将计数设置到DEPARTMENT中的哪个部门ID。 what exactly does this subquery return "select count(*) from EMPLOYEE e where p.dept_id = e.dept_id" 该子查询返回的确切内容是“从EMPLOYEE e中选择count(*),其中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). 因此,基于外部查询(即具有department表)执行内部查询。 If, your outer query has total 3 records then, inner query (ie has EMPLOYEE table) will get execute three times. 如果您的外部查询总共有3条记录,那么内部查询(即具有EMPLOYEE表)将被执行3次。

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 . 在您的方案中,您已将外部查询中具有dept_id的查询映射到外部查询,因此这将查询内部查询(即EMPLOYEE表)并基于dept_id获取计数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM