SQL:获取所有客户的最新付款?

时间:2011-04-11 11:53:27

标签: mysql sql join

即时通讯使用Mysql 5.1并使用列customerid付款,付款日期我需要所有客户的最新付款。 所以带有条目的表

row, customerid, paymentdate
1    5           2011-03-01
2    5           2011-04-01
3    6           2011-01-01
4    7           2011-01-01
5    7           2011-02-01

应该返回2,3,5行 查询

select max(paymentdate),customerid from payments where customerid=5;

我试图进入某种WHERE客户IN(...),但没有运气,因为它返回2列不仅1

感谢


最后答案激发了我找到相关信息并解决了问题 以下查询(如文章评论中所述)

select * from (select * from payments order by paymentdate desc) as p group by customerid;

same problem from mysql forum solutions from a related mysql article

2 个答案:

答案 0 :(得分:5)

您应该group by customerid。

select max(paymentdate),customerid from payments group by customerid;

答案 1 :(得分:-1)

另一种方法:

Select paymentdate,customerid from payments group by customerid order by paymentdate DESC;

甚至:

Select distinct(customerid),paymentdate from payments order by paymentdate DESC;

按顺序添加DESC会导致首先返回最近的日期。