SQL查询:过去90天内没有付款

时间:2011-04-26 19:40:02

标签: mysql sql

假设我的客户有很多付款。如何查询以获取过去90天内没有付款记录的所有客户?

clients
=======
id          integer
name        string

payments
========
id          integer
client_id   integer
created_at  datetime

基本上是反过来:

select *
from clients
inner join payments on payments.client_id = clients.id
where payments.created_at > utc_timestamp() - interval 90 day

希望比以下更有效率:

select *
from clients 
where id not in (
  select *
  from clients
  inner join payments on payments.client_id = clients.id
  where payments.created_at > utc_timestamp() - interval 90 day
)

2 个答案:

答案 0 :(得分:1)

确保payments(client_id)上有索引,甚至更好,payments(client_id, created_at)。

有关编写查询的替代方法,您可以尝试not exists,例如:

select  *
from    clients c
where   not exists
        (
        select  *
        from    payments p
        where   p.payments.client_id = clients.id
                and payments.created_at > utc_timestamp() - interval 90 day
        )

或专属左连接:

select  *
from    clients c
left join
        payments p
on      p.payments.client_id = clients.id
        and payments.created_at > utc_timestamp() - interval 90 day
where   p.client_id is null

如果两者都很慢,请在问题中添加explain extended输出,以便我们了解原因。

答案 1 :(得分:0)

select *
from clients
left join payments on 
    payments.client_id = clients.id and 
    payments.created_at > utc_timestamp() - interval 90 day
where payments.client_id is null