使用WHERE子句和在SELECT子句中使用JOIN的区别

huangapple go评论60阅读模式
英文:

difference between joining with WHERE AND JOIN in SELECT clause

问题

第一个查询返回:

ORA-01427: 单行子查询返回多行
01427. 00000 -  "单行子查询返回多行"

第二个查询可以正常运行并返回数据。我明白第一个查询返回多于一行的结果,因为我可以单独运行子查询来检查。但让我困惑的是第二个查询如何只返回一行?我的结果不是单行,而是多行。

英文:

I have two queries:

select id,(SELECT N.NAME
        FROM memuat.NETWORK N 
        join memuat.host H
        on N.ID = H.NETWORK ) as network_name
from memuat.host;
        
select id,(SELECT N.NAME
        FROM memuat.NETWORK N
        where N.ID = H.NETWORK ) as network_name
from memuat.host H;

The first returns:

ORA-01427: single-row subquery returns more than one row
01427. 00000 -  "single-row subquery returns more than one row"

the second runs fine and returns data. It is clear to me that the first returns more than one row , because I can run the sub-query alone and check that. What it's not clear to me is how the second query can return only one row ? My result is not a single row, it's multiple rows.

答案1

得分: 1

在两个查询中,子查询会针对每个主机行执行一次。

在您的第二个查询中,子查询是:

选择n.name from memuat.network n where n.id = h.network

这获取了主机的网络ID对应的网络名称。

在您的第一个查询中,子查询是:

选择n.name
从memuat.network n中
加入memuat.host h ON n.id = h.network

这获取了网络名称的列表。可能有许多重复项,因为我们会针对每个主机获得一行。

在这两种情况下的主查询是:

选择id,(<子查询>) AS network_name
从memuat.host h中;

在这里,子查询应该返回一个值,即主机的网络名称。由于您的第二个查询中的子查询返回了一行一个值,因此它有效。而在您的第一个查询中的子查询返回了多行,因此会导致错误。

英文:

In both queries, the subquery gets executed once per host row.

In your second query the subquery is:

select n.name from memuat.network n where n.id = h.network

This gets the network name for the host's network ID.

In your first query the subquery is:

SELECT n.name
FROM memuat.network n 
JOIN memuat.host h ON n.id = h.network

This gets list of network names. Probably with many duplicates, because we get one row per host.

The main query in both cases is:

SELECT id, ( &lt;subquery&gt; ) AS network_name
FROM memuat.host h;

Here the subquery is supposed to return one value, namely the host's network name. As the subquery in your second query returns one row with one value, this works. As the subquery in your first query returns many rows, you get an error.

huangapple
  • 本文由 发表于 2023年2月14日 18:45:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75446716.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定