使用group by / order by执行MSQL查询

时间:2018-02-06 16:05:19

标签: mysql

我正在处理个人收件箱。这是我的收件箱表:

收件箱

  

email - createdDate - message

     

mail1@test.com - 12/02/2017 - message1
  mail1@test.com - 2017年2月13日 - message2
  mail3@test.com - 2017年2月14日 - message3
  mail2@test.com - 2017年2月10日 - message4
  mail2@test.com - 05/02/2017 - message5
  mail3@test.com - 11/02/2017 - message6
  mail3@test.com - 16/02/2017 - message7

查询后我想要的是什么:

  

电子邮件 - createdDate - 消息
  mail3@test.com - 16/02/2017 - message7
  mail1@test.com - 2017年2月13日 - message2
  mail2@test.com - 2017年2月10日 - message4

我已经尝试了分组依次和左右连接的一些事情,但需要花费很多时间才能完成。

我目前的查询是:

SELECT a.email, a.createdDate, a.message FROM inbox a LEFT JOIN inbox b ON (a.email = b.email AND a.createdDate < b.createdDate)WHERE b.createdDate IS NULL ORDER BY a.createdDate DESC LIMIT 0,20

我也在我的电子邮件和createdDate字段上创建了索引。 能否帮助我通过执行mysql查询得到这个结果? 非常感谢..

1 个答案:

答案 0 :(得分:0)

首先对您的子查询进行排序,然后只选择group by所选列:

select * from (select email, STR_TO_DATE(createdDate, '%d/%m/%Y') as myDate, message from inbox order by myDate desc) as t
 group by email

如果同一天可能有多封电子邮件,您的表格中应该有一个id列(我认为是这样),那么您需要在订单中添加id DESC: / p>

select * from (select email, STR_TO_DATE(createdDate, '%d/%m/%Y') as myDate, message from inbox order by myDate desc, id desc) as t
 group by email
相关问题