简体   繁体   English

Oracle在SQL查询中使用变量

[英]Oracle use variable in in SQL query

I have something like this: 我有这样的事情:

With a as (select id from table_a)
select * from table_b where table_b.id > (select min(id) from a)

table_a is a huge table with millions of records and I don't want to go through all the records to find the min(i) every time I want to use min(i). table_a是一个巨大的表,具有数百万个记录,并且我不想每次使用min(i)都要遍历所有记录来查找min(i)。 Is there any way for me to store the min(id) in a variable and use it in the query? 有什么办法可以将min(id)存储在变量中并在查询中使用它? Something like this : 像这样的东西:

With a as (select id from table_a),
b as ((select min(id) into min_id from a))
select * from table_b where table_b.id > min_id

Your query should be doing what you want. 您的查询应该在做您想要的。 But, if you really want to be sure, move the subquery to the from clause: 但是,如果您确实希望确定,请将子查询移至from子句:

select b.*
from table_b b join
     (select min(id) as min_id from a) a
     on b.id > a.min_id;

You may help Oracle by defining an index on the table_a on column id to not go through all the records to find the min . 您可以通过在table_a上的列id上定义一个索引而不通过所有记录来查找min来帮助Oracle。

If the index is defined, Oracle performs a single index access to get the minimal row. 如果定义了索引,Oracle将执行单个索引访问以获取最小行。

Without the index, you'll hav eto perform one FULL TABLE SCAN of the large table. 没有索引,您将不得不执行大表的一次FULL TABLE SCAN

The best way to verify is to observe the execution plan: 验证的最佳方法是遵守执行计划:

 create index idx_a on table_a(id);  

EXPLAIN PLAN  SET STATEMENT_ID = 'q1' into   plan_table  FOR
With a as (select id from table_a)
select * from table_b 
where table_b.id > (select min(id) from a);
SELECT * FROM table(DBMS_XPLAN.DISPLAY('plan_table', 'q1','ALL')); 

---------------------------------------------------------------------------------------
| Id  | Operation                   | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT            |         |  5524 | 71812 |    49   (3)| 00:00:01 |
|*  1 |  TABLE ACCESS FULL          | TABLE_B |  5524 | 71812 |    47   (3)| 00:00:01 |
|   2 |   SORT AGGREGATE            |         |     1 |    13 |            |          |
|   3 |    INDEX FULL SCAN (MIN/MAX)| IDX_A   |     1 |    13 |     2   (0)| 00:00:01 |
---------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter("TABLE_B"."ID"> (SELECT MIN("ID") FROM "TABLE_A" "TABLE_A"))

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

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