非活动客户mysql查询优化

时间:2013-07-26 09:54:11

标签: mysql

我有一张拥有数百万条记录的客户表。 客户

id | name | ..... 

我还有一个带

的订单表
id | custID | orderDate | ....

我需要找到所有未下订单超过30天的人。还应该包括那些从未下过订单的人

select name,customer.id from customer where id in 

(select custID from orders where datediff(curdate(),orders.orderDate) > 30 )

union

select name,customer.id from customer  left join orders on customer.id = orders.custID where orders.id is null

如何优化查询?

2 个答案:

答案 0 :(得分:1)

尝试

select name,t.id 
  from customer t where 
    not exists (
        select 1 
          from orders where 
          custID=t.id
          and
          datediff(curdate(),orders.orderDate) <= 30 )

答案 1 :(得分:1)

试试这个

Select Customer.Custid,
Customer.name
from Customer
left join orders on 
customer.custid = orders.custid and
datediff(getdate(),orders.orderdate)>30)

where 
orders.id is null