oracle中select语句中的子查询是如何工作的

2021-12-19 00:00:00 sql group-by select subquery oracle

我已经翻遍了关于select语句中的子查询如何工作的解释,但由于非常模糊的解释,我仍然无法理解这个概念.

I have looked all over for an explanation, to how does the subquery in a select statement work and still I cannot grasp the concept because of very vague explanations.

我想知道你如何在oracle的select语句中使用子查询以及它究竟输出什么.

I would like to know how do you use a subquery in a select statement in oracle and what exactly does it output.

例如,如果我有一个查询想要显示员工的姓名以及他们从这些表中管理的个人资料数量

For example, if i had a query that wanted to display the names of employees and the number of profiles they manage from these tables

员工(EmpName, EmpId)

Employee(EmpName, EmpId)

配置文件(ProfileId, ..., EmpId)

Profile(ProfileId, ..., EmpId)

如何使用子查询?

我想在 select 语句中需要一个子查询来实现 group by 函数来计算每个员工管理的配置文件的数量,但我不太确定.

I was thinking a subquery is needed in the select statement to implement the group by function to count the number of profiles being managed for each employee, but I am not too sure.

推荐答案

很简单-

SELECT empname,
       empid,
       (SELECT COUNT (profileid)
          FROM profile
         WHERE profile.empid = employee.empid)
           AS number_of_profiles
  FROM employee;

当你使用像这样的表连接时,它会更简单:

It is even simpler when you use a table join like this:

  SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
    FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;

<小时>

对子查询的解释:

本质上,select 中的子查询获取标量值并将其传递给主查询.select 中的子查询不能传递多于一行和多于一列,这是一个限制.在这里,我们将一个 count 传递给主查询,正如我们所知,它始终只是一个数字——一个标量值.如果未找到值,子查询将 null 返回到主查询.此外,子查询可以访问主查询的 from 子句中的列,如我的查询所示,其中 employee.empid 从外部查询传递到内部查询.

Essentially, a subquery in a select gets a scalar value and passes it to the main query. A subquery in select is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null to the main query. Moreover, a subquery can access columns from the from clause of the main query, as shown in my query where employee.empid is passed from the outer query to the inner query.

编辑:

当您在 select 子句中使用子查询时,Oracle 本质上将其视为左连接(您可以在 为您的查询解释计划),对于左侧的每一行,行的基数只是右侧的一个.

When you use a subquery in a select clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.

左连接说明

左连接非常方便,特别是当你想替换 select 子查询时,因为它的限制.此处对LEFT JOIN 关键字两侧的表的行数没有限制.

A left join is very handy, especially when you want to replace the select subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN keyword.

有关详细信息,请阅读 关于子查询的 Oracle 文档 和 左连接或左外连接.

For more information read Oracle Docs on subqueries and left join or left outer join.

相关文章