我有客户表和另一个与他们相关的销售活动(电话,电子邮件ecc)。我需要知道的是,例如,这些客户中有哪些在过去30天内没有联系过(没有活动)。
这是我想要做的:
SELECT crm_customers.id, crm_ customers.companyname
FROM crm_ customers
LEFT JOIN crm_activities on crm_customers.id = crm_ activities. Customerid
WHERE crm_ activities.createddate < (getDate() – 30)问题是,即使客户最近有活动,它也会返回活动超过30天的客户。我只需要得到在过去30天内没有任何销售活动的客户,谢谢你的帮助
发布于 2012-10-10 02:05:48
SELECT crm_customers.id, crm_customers.companyname
FROM crm_customers
LEFT JOIN crm_activities
on crm_customers.id = crm_activities.Customerid
and DATEDIFF(DD, crm_activities.createddate, getdate()) < 30
where crm_activities.Customerid is null这是连接中的条件与where中的条件不同的情况
为了提高速度,我怀疑对子查询的连接。它为查询优化器提供了更多的优化选项。不需要distinct。假设crm_activities.Customerid被编入索引,这是对索引的连接。对于子查询,它将使用索引来创建列表,但是子查询的输出不会被索引。
将取决于你的数据。我有一张大桌子可以测试。
查询计划不同。
在循环连接上,散列连接的速度是合并连接的两倍,是十倍
如果没有被排除,那么它将是死气沉沉的。
如果许多人被排除在外(在过去30年中已经联系过),它将出现在哪里。
发布于 2012-10-10 01:38:46
这可能会对您有所帮助:使用子查询:
select
cust.id, cust.compayname
from
crm_customers as cust
left join (
select
*
from
crm_activities
where
createddate >= (getDate() - 30)
) as act on cust.id = act.customerId
where
act.customerId is null这样就排除了在过去30天内有活动的所有客户。
您可能希望通过执行以下操作进一步清理此问题:
select
cust.id, cust.compayname
from
crm_customers as cust
left join (
select distinct
customerId
from
crm_activities where createddate >= (getDate() - 30)
) as act on cust.id = act.customerId
where
act.customerId is null这是相同的基本思想..。唯一的问题是,第二个选项只返回包含活动的客户的Ids。我认为这可能会优化外部where子句,但它可能对子查询的性能产生影响(没有免费的午餐)
https://stackoverflow.com/questions/12805342
复制相似问题