Question

I have this tables,

user
  id
  name

visit
  id
  id_user (fk user.id)
  date
  comment

If i execute this query,

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

I get,

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

If I GROUP BY u.id, then I get

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

I need the last visit from Jhon

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

I try this

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

And this,

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)

And I get

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

But this is not valid to me... I need the last visit from this user

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

Thanks!

Was it helpful?

Solution

This should give you the last comment for every user:

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

OTHER TIPS

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;

use:

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

Will show 1 record order by date.

Hope will help!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top