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
How to use the Output of one SQL Statement in another
提问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
回答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 in
and 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,因为:
IN
in Oracle has a limit of 1,000 valuesEXISTS
allows you to match on more than one column if necessaryEXISTS
returns 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 EXISTS
as a correlated subquery, but it executes differently & doesn't evaluate the SELECT
clause - 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')