我有2个表格(AllClients
& 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'";
答案 0 :(得分: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 :(得分: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'";
答案 2 :(得分: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
。