2013-10-09 87 views
1

我有2個表(AllClients & AllActivities),並需要檢索以下信息:需要幫助提高SQL性能(子查詢與聯接)

我需要在那裏最近的活動已被輸入不同的客戶名單去年。我已經得到了下面的代碼來工作,但它很痛苦地慢,因此沒有用。我相信一個連接(沒有子查詢)會更快,但我無法弄清楚。這是我當前的SQL語句:

select distinct(AllClients.LookupCode) 
from AllClients 
join (select LookupCode, 
       max(AllActivities.EnteredDate) as EnteredDate 
     from AllActivities 
     group by LookupCode) AllActivities 
on  AllClients.LookupCode = AllActivities.LookupCode 
where AllClients.Name = '$userName' 
and  AllClients.TypeCode = 'P' and AllActivities.EnteredDate < '$oneYearAgo'"; 
+0

子查詢看起來很好。你可以先在'EnteredDate'上添加條件,而不是在主查詢中進行。 – Sebas

回答

2

試試這個:

select AllClients.LookupCode 
from AllClients 
join AllActivities on AllClients.LookupCode = AllActivities.LookupCode 
where AllClients.Name = '$userName' and AllClients.TypeCode = 'P' 
group by AllClients.LookupCode 
having max(AllActivities.EnteredDate) < '$oneYearAgo'; 
+1

這是做到了!快多了!!!謝謝!!! – daytonk

1

你的意思是這樣?

SELECT AllClients.LookupCode 
    FROM AllClients 
    JOIN AllActivities 
     ON AllClients.LookupCode = AllActivities.LookupCode 
    WHERE AllClients.Name = '$userName' 
    AND AllClients.TypeCode = 'P' 
GROUP BY AllClients.LookupCode 
    HAVING MAX(AllActivities.EnteredDate) < '$oneYearAgo'"; 
+0

哇...這是我見過的最好的查詢格式! –

+0

@ClaudioSantos你這樣說格式?然後把它投票;) – mucio

+1

沒有問題是關於查詢性能不查詢格式化... :) –

0

你不需要做聚合。

select distinct(AllClients.LookupCode) 
from AllClients 
where 
     AllClients.Name = '$userName' 
and  AllClients.TypeCode = 'P' 
and  exists (
    select 1 from AllActivities where AllClients.LookupCode = AllActivities.LookupCode and AllActivities.EnteredDate > '$oneYearAgo' 
) 

我甚至不確定在這個配置中需要distinct