考虑以下(诚然很长)示例。
示例代码创建了两个数据集,数据一具有“键”变量 i、j、k,数据二具有键变量 j、k 和“值”变量 x。我想尽可能有效地合并这两个数据集。两个数据集都针对 j 和 k 进行了索引:不应该需要第一个数据的索引,但无论如何它都在那里。
Proc SQL 不使用数据二中的索引,我想如果数据在关系数据库中就会出现这种情况。这只是我必须接受的查询优化器的限制吗?
编辑:这个问题的答案是肯定的,SAS 可以使用索引来优化 PROC SQL 连接。在以下示例中,数据集的相对大小很重要:如果您修改代码使数据二变得相对大于数据一,则将使用索引。数据集是否排序无关紧要。
* Just to control the size of the data;
%let j_max=10000;
* Create data sets;
data one;
do i=1 to 3;
do j=1 to &j_max;
do k=1 to 4;
if ranuni(0)<0.9 then output;
end;
end;
end;
run;
data two;
do j=1 to &j_max;
do k=1 to 4;
x=ranuni(0);
if ranuni(0)<0.9 then output;
end;
end;
run;
* Create indices;
proc datasets library=work nolist;
modify one;
index create idx_j_k=(j k);
modify two;
index create idx_j_k=(j k) / unique;
run;quit;
* Test the use of an index for the other data set:
* Log should display "INFO: Index idx_j_k selected for WHERE clause optimization.";
options msglevel=i;
data _null_;
set two(where=(j<100));
run;
* Merge the data sets with proc sql - no index is used;
proc sql;
create table onetwo as
select
one.*,
two.x
from one, two
where
one.j=two.j and
one.k=two.k;
quit;