MySQL在过去6周内没有创建发票的客户

时间:2014-01-17 11:47:34

标签: mysql client datediff invoice maxdate

我很难列出过去6周内没有创建发票的所有客户。涉及两个表,客户和发票。 我当前的查询如下所示:

select MAX(invoice.created_date) 'Last Invoice Date', invoice.invoice_no 'Invoice No.', DATEDIFF(curdate(), max(invoice.created_date)) 'Days since last invoice created', client.name 'Client'  
from invoice 
left join
client on invoice.client_id = client.id 
where 
datediff (curdate(), (select MAX(invoice.created_date) from invoice left join client on invoice.client_id = client.id)) >  42
group by client.id;

但它返回一个空集。 任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

从发票开始加入意味着立即排除任何没有发票的客户。您可以从客户端开始并加入发票,以便在select中获取所需信息,然后使用EXISTS子句仅获取过去x天内没有发票的客户:

SELECT MAX(invoice.created_date) 'Last Invoice Date', invoice.invoice_no 'Invoice No.', DATEDIFF(curdate(), max(invoice.created_date)) 'Days since last invoice created', client.name 'Client'  
FROM client c
LEFT JOIN invoice i ON (i.client_id = c.id)
WHERE NOT EXISTS(
    SELECT 1 FROM invoice i2
    WHERE i2.client_id = c.id
    AND DATE_SUB(NOW(), INTERVAL 42 DAY) < i2.created_date
)
GROUP BY c.id;