【轉載】在ABAP中用for all entries in代替inner join
在ABAP中用for all entries in代替inner join
取資料一般都會用到多個表,inner join是非常常用的操作,但因為比較耗資料庫資源,所以很多時間不推薦。
大家也知道,SAP這東西,應用伺服器可以擴充套件為多個,但資料庫伺服器只有一個,所以必須少消耗DB資源。
據boss說,一般多對多或關聯很多表(例如3個以上)時就不用inner join(前者是因為難搞清關係,不太清晰),應改成for all entries in。
header-item或多對一關係就可以inner join(即另一張表的where語句上所有的key都唯一確定了)。
下面給個例子(老師寫的程式碼,稍微改動了一下):
report ztest_jion.
initialization.
tables : vbak.
types : begin of ty_vbak,
vbeln type vbeln_va,
erdat type erdat,
kunnr type kunag,
end of ty_vbak.
types : begin of ty_vbap,
vbeln type vbeln_va,
posnr type posnr,
matnr type matnr,
end of ty_vbap.
types : begin of ty_fin,
vbeln type vbeln_va,
erdat type erdat,
kunnr type kunag,
posnr type posnr,
matnr type matnr,
end of ty_fin.
data : t_vbak type standard table of ty_vbak,
t_vbap type standard table of ty_vbap,
t_fin_all type standard table of ty_fin,
t_fin_join type standard table of ty_fin,
w_vbak type ty_vbak ,
w_vbap type ty_vbap ,
w_fin type ty_fin.
select-options : s_vbeln for vbak-vbeln.
start-of-selection.
select
vbak~vbeln
vbak~erdat
vbak~kunnr
vbap~posnr
vbap~matnr
into table t_fin_join
from vbak inner join vbap
on vbak~vbeln = vbap~vbeln
where vbak~vbeln in s_vbeln.
if sy-subrc <> 0.
write : 'No data.'.
exit.
endif.
select
vbeln
erdat
kunnr
from vbak
into table t_vbak
where vbeln in s_vbeln.
if t_vbak[] is not initial.
select
vbeln
posnr
matnr
from vbap
into table t_vbap
for all entries in t_vbak
where vbeln = t_vbak-vbeln.
endif.
end-of-selection.
write : / 'Inner jion:',
/ 'Sales Document',
20 'Create Date',
40 'Sold-to party',
60 'Sales Document Item',
80 'Material Number'.
sort t_fin_join.
loop at t_fin_join into w_fin.
write : / w_fin-vbeln,
20 w_fin-erdat,
40 w_fin-kunnr,
60 w_fin-posnr,
80 w_fin-matnr.
endloop.
skip.
loop at t_vbap into w_vbap.
w_fin-vbeln = w_vbap-vbeln.
w_fin-posnr = w_vbap-posnr.
w_fin-matnr = w_vbap-matnr.
read table t_vbak into w_vbak with key
vbeln = w_vbap-vbeln.
if sy-subrc = 0.
w_fin-erdat = w_vbak-erdat.
w_fin-kunnr = w_vbak-kunnr.
endif.
append w_fin to t_fin_all.
clear w_fin.
endloop.
sort t_fin_all.
write : / 'For all entries in:',
/ 'Sales Document',
20 'Create Date',
40 'Sold-to party',
60 'Sales Document Item',
80 'Material Number'.
loop at t_fin_all into w_fin.
write : / w_fin-vbeln,
20 w_fin-erdat,
40 w_fin-kunnr,
60 w_fin-posnr,
80 w_fin-matnr.
endloop.
1個inner join變成了3段程式碼,看上去貌似很不值得,但還是分析下程式碼吧。
第一個是將vbak和vbap這2個表在vbeln相等的條件下進行inner join。
第二個則先從vbak中提取資料放入t_vbak。
再從vbap中提取所有vbeln = t_vbak-vbeln的資料放入t_vbap。
最後再遍歷t_vbap,並從t_vbak讀取相應資料,構造一個t_fin_all。
至此,t_fin_join和t_fin_all的資料就相同了(只是順序不同,排序下就一樣了)。
http://www.cnblogs.com/VerySky/articles/2277130.html