1

我有一个包含数百万条记录的客户表。顾客

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

如何优化查询?

4

2 回答 2

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 )
于 2013-07-26T10:00:28.160 回答
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
于 2013-07-26T10:05:03.087 回答