2013-10-09 57 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