我有一张拥有数百万条记录的客户表。 客户
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
如何优化查询?
答案 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