oracle 如何在另一个 SQL 语句中使用输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7271588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 00:17:17  来源:igfitidea点击:

How to use the Output of one SQL Statement in another

sqloracleoracle11g

提问by Display Name

I have the following statement:

我有以下声明:

select region_id from regions
where region_name = 'Europe' 

I need the Output from this in the following statement where 'bla' is:

我需要以下语句中的输出,其中 'bla' 是:

select count(*) from countries
where region_id = 'bla'

How can I do that?

我怎样才能做到这一点?

回答by mcabral

Try the IN clause

试试IN 子句

select distinct * from countries
where region_id IN (select region_id from regions
where region_name = 'Europe')

回答by Blindy

Subqueries to the rescue!

子查询来救援!

select distinct * 
from countries
where region_id=(select top 1 ir.region_id 
                 from regions ir
                 where ir.region_name = 'Europe' )

Alternatively, you can use inand give it a list of items returned from your query.

或者,您可以使用in并为其提供从查询返回的项目列表。

回答by OMG Ponies

Using EXISTS:

使用存在:

SELECT c.* 
  FROM COUNTRIES c
 WHERE EXISTS (SELECT NULL 
                 FROM REGIONS r
                WHERE r.region_id = c.region_id
                  AND r.region_name = 'Europe')

My preference is to use EXISTS rather than IN because:

我更喜欢使用 EXISTS 而不是 IN,因为:

  • INin Oracle has a limit of 1,000 values
  • EXISTSallows you to match on more than one column if necessary
  • EXISTSreturns true on the first match, which can be faster than IN/etc depending on needs
  • IN在 Oracle 中有 1,000 个值的限制
  • EXISTS允许您在必要时匹配多列
  • EXISTS在第一次匹配时返回 true,根据需要,它可以比 IN/etc 更快

Most mistake EXISTSas a correlated subquery, but it executes differently & doesn't evaluate the SELECTclause - you can test using:

大多数错误都EXISTS作为相关子查询,但它的执行方式不同并且不评估SELECT子句 - 您可以使用以下方法进行测试:

SELECT c.* 
  FROM COUNTRIES c
 WHERE EXISTS (SELECT 1/0
                 FROM REGIONS r
                WHERE r.region_id = c.region_id
                  AND r.region_name = 'Europe')