MySQL每用户一行取决于maxDate或maxId


MySQL one row per user depending on maxDate or maxId

我在MYSQL中有一个名为enrollment的表,其中包含以下字段:id, user, estimated_date.

本例中的值为:

id, user, estimated_date
1, 1, 2015-10-10
2, 1, 2015-10-10
3, 2, 2015-10-20
4, 2, 2015-10-10

我想为每个用户选择一行:具有max(estimated_date)的行。但是在estimated_date相等的情况下,必须选择具有max(id)的那个。换句话说……按estimated_date和id排序的组

输出应该是:

2, 1, 2015-10-10
3, 2, 2015-10-20

我现在有了这个代码:

    SELECT * from enrollments m 
INNER JOIN
  (SELECT user,
          max(estimated_date) AS maxdate
   FROM enrollments
   GROUP BY user
  ) x ON m.user = x.user
AND m.estimated_date = x.maxdate

你能帮我吗?我一直在找,但没有找到任何适合这个案子的东西。谢谢!

你不需要一个INNER JOIN,一个ORDER by estimated_date DESC, id DESC就足够了。这是你的查询:

Select * FROM (
SELECT
  DISTINCT  `id`, `user`, `estimated_date`
FROM
  enrollments  
ORDER by estimated_date DESC, id DESC
  ) as X
  GROUP BY user

完整的小提琴在这里:http://sqlfiddle.com/#!9/31799/3