简体   繁体   English

需要帮助提高SQL性能(子查询与连接)

[英]Need help improving SQL performance (subquery versus join)

I have 2 tables ( AllClients & AllActivities ) and need to retrieve the following information: 我有2个表( AllClientsAllActivities ),需要检索以下信息:

I need a list of distinct clients where the most recent activity has been entered in the last year. 我需要一个不同客户的列表,其中最近一次活动是在去年输入的。 I've gotten the following code to work, but it is painfully slow and therefore not useful. 我已经得到了以下代码,但它很慢,因此无用。 I believe a join (without the subquery) will be faster, but I just can't figure it out. 我相信一个连接(没有子查询)会更快,但我无法弄明白。 Here is my current sql statement: 这是我当前的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'";

try this: 尝试这个:

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';

do you mean something like this? 你的意思是这样的吗?

  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'";

you don't need to do the aggregate. 你不需要做聚合。

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'
)

I'm not even sure you need the distinct either in this configuration. 我甚至不确定你是否需要在这种配置中distinct

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM