简体   繁体   English

MYSQL:从多个列中选择MAX日期

[英]MYSQL: Select MAX date from multiple columns

I'm having trouble with a SQL query. 我在使用SQL查询时遇到问题。 This is my purchase table: 这是我的购买表:

id       email                status       date
1        user1@server.com     confirmed    2014-10-01
2        user1@server.com     confirmed    2014-10-02
3        user2@server.com     pending      2014-10-02
4        user3@server.com     pending      2014-10-02
5        user1@server.com     pending      2014-10-03
6        user3@server.com     pending      2014-10-03
7        user1@server.com     pending      2014-10-04
8        user2@server.com     pending      2014-10-04
9        user2@server.com     pending      2014-10-05

I want to select the most recent pending purchase for each email, so the result I'm expecting is: 我想为每封电子邮件选择最近的未决购买,所以我期望的结果是:

id      email                 status       date
6       user3@server.com      pending      2014-10-03
7       user1@server.com      pending      2014-10-04
9       user2@server.com      pending      2014-10-05

Any ideas how I can achieve this? 有什么想法可以实现这一目标吗?
Thanks in advance. 提前致谢。

You can do this with a subquery: 您可以使用子查询来执行此操作:

select p.*
from purchase p join
     (select email, max(id) as maxid
      from purchase
      where status = 'pending'
      group by email
     ) pmax
     on p.id = pmax.maxid;

This assumes that "most recent" is the one with the largest id . 假定“最新”是id最大的那个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM