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

Mysql 需要帮助提高SQL性能(子查询与联接),mysql,sql,Mysql,Sql,我有两个表AllClient&AllActivities,需要检索以下信息: 我需要一个不同客户的名单,其中最近的活动已进入去年。我已经使用了下面的代码,但是速度非常慢,因此没有用处。我相信没有子查询的连接会更快,但我就是想不出来。以下是我当前的sql语句: select distinct(AllClients.LookupCode) from AllClients join (select LookupCode, max(AllActivit

我有两个表AllClient&AllActivities,需要检索以下信息:

我需要一个不同客户的名单,其中最近的活动已进入去年。我已经使用了下面的代码,但是速度非常慢,因此没有用处。我相信没有子查询的连接会更快,但我就是想不出来。以下是我当前的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'";
试试这个:

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

你是说像这样的事吗

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

您不需要进行聚合

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。

子查询似乎很好。您可以先将EnteredDate上的条件添加到其中,而不是在主查询外部执行。@ClaudioSantos您这样说是为了格式化吗?然后投票表决;否问题是关于查询性能而不是查询格式…:很公平,那么为什么是最好的问题呢