GROUP BY最后一天MYSQL

时间:2013-12-04 13:51:16

标签: mysql sql date group-by having

我有这个表,

user
  id
  name

visit
  id
  id_user (fk user.id)
  date
  comment

如果我执行此查询,

SELECT u.id, u.name, e.id, e.date, e.comment
FROM user u
LEFT JOIN visit e ON e.id_user=u.id

我明白了,

1 Jhon 1 2013-12-01 '1st Comment' 
1 Jhon 2 2013-12-03 '2nd Comment' 
1 Jhon 3 2013-12-01 '3rd Comment'

如果我GROUP BY u.id,那么我

1 Jhon 1 2013-12-01 '1st Comment'

我需要Jhon的最后一次访问

1 Jhon 3 2013-12-04 '3rd Comment'

我试试这个

SELECT u.id, u.name, e.id, MAX(e.date), e.comment
FROM user u
LEFT JOIN visit e ON e.id_user=u.id
GROUP BY u.id

而且,

SELECT u.id, u.name, e.id, MAX(e.date), e.comment
FROM user u
LEFT JOIN visit e ON e.id_user=u.id
GROUP BY u.id 
HAVING MAX(e.date)

我得到了

1 Jhon 1 2013-12-04 '1st Comment'

但这对我无效......我需要此用户的最后一次访问

1 Jhon 3 2013-12-01 '3rd Comment'

谢谢!

3 个答案:

答案 0 :(得分:2)

这应该为您提供每个用户的最后评论:

SELECT u.id, u.name, e.id, e.date, e.comment
FROM user u
LEFT JOIN (SELECT t1.*
  FROM visit t1
    LEFT JOIN visit t2
      ON t1.id_user = t2.id_user AND t1.date < t2.date
  WHERE t2.id_user IS NULL
  ) e ON e.id_user=u.id

答案 1 :(得分:1)

SELECT u.id, u.name, e.id, e.date, e.comment
FROM user u
LEFT JOIN visit e ON e.id_user=u.id
ORDER BY e.date desc
LIMIT 1;

答案 2 :(得分:0)

使用:

SELECT u.id, u.name, e.id, e.date, e.comment FROM user u LEFT JOIN visit e ON e.id_user=u.id order by e.date DESC limit 0,1

按日期显示1条记录。

希望会有所帮助!