MySQL加入条件即时加入

时间:2012-04-24 04:30:46

标签: mysql

我需要知道,我如何在飞行中做到这一点,

例如我有各自不同的duedate状态的客户,我想选择MAX(最近到期日)ON LEFT JOIN当前当它连接两个表时它选择最老的duedate,这不是我想要的..

SELECT c.customerid, i.datedue
                        FROM  customers c
                               LEFT JOIN invoice i 
                                 ON i.customerid = c.customerid
                        WHERE  i.datedue <= UNIX_TIMESTAMP()
                               AND c.status!='d'
                        GROUP  BY i.customerid
                        ORDER BY i.datedue DESC
                        LIMIT  0, 1000

1 个答案:

答案 0 :(得分:2)

您需要使用max()函数:

SELECT c.customerid, MAX(i.datedue)
FROM customers c LEFT JOIN invoice i ON i.customerid = c.customerid
WHERE i.datedue <= UNIX_TIMESTAMP() and c.status!='d'
GROUP BY i.customerid
ORDER BY i.datedue DESC
LIMIT 0,1000

这将为您提供每位客户的最大日期。