34,836
社区成员




-- 建索引
create nonclustered index ix_B_VfUID on B(VfUID)
create nonclustered index ix_D_OctObjectGuid on D(OctObjectGuid)
-- 新写法
if object_id('tempdb..#t1') is not null
drop table #t1
select t1.TradeCode,
t1.OrderNO,
t1.CreateTime,
t1.BusinessType,
t1.BuyerID,
t1.SellerID
into #t1
from A t1
where t1.BusinessType in(1,2)
and t1.IsEffective=1
and t1.TradeStatus=4
and t1.CreateTime<getdate()
if object_id('tempdb..#t2') is not null
drop table #t2
select VfUID=convert(nvarchar(50),t2.VfUID),
t2.OctObjectGuid,
t2.VfAdminLoginName
into #t2
from B t2
inner join (select distinct bs=BuyerID from #t1
union
select distinct bs=SellerID from #t1) t1 on convert(nvarchar(50),t2.VfUID)=t1.bs
if object_id('tempdb..#t4') is not null
drop table #t4
select OctObjectGuid=convert(nvarchar(50),t4.OctObjectGuid),
t4.UnBindDate
into #t4
from D t4
inner join (select distinct bs=BuyerID from #t1
union
select distinct bs=SellerID from #t1) t1 on convert(nvarchar(50),t4.OctObjectGuid)=t1.bs
select
t1.TradeCode,
t1.OrderNO,
t1.CreateTime,
payer=case t1.BusinessType
when 1 then isnull(t3.Account,t2.VfAdminLoginName)
when 2 then 'XXX' end,
payee=case t1.BusinessType
when 1 then 'XXX'
when 2 then isnull(t3.Account,t2.VfAdminLoginName) end,
PAYTYPE='payment',
t4.UnBindDate,
TRADE_SRC_VOUCHER_NO=t1.TradeCode
from #t1 t1
left join #t2 t2 on t1.BuyerID=t2.VfUID or t1.SellerID=t2.VfUID
left join C t3 on t2.OctObjectGuid=t3.Guid
left join #t4 t4 on t1.BuyerID=t4.OctObjectGuid or t1.SellerID=t4.OctObjectGuid
SELECT *
FROM A
LEFT JOIN B ON A.ID=B.ID
LEFT JOIN C ON B.TID=C.ID
union
SELECT *
FROM A
LEFT JOIN B ON A.ID=B.ID
LEFT JOIN C ON B.KID=C.ID