0

I have a comments table and allow people to edit their comments. Instead of overwriting comments I create a new comment and associate it to its "parent". Additionally, I add the child information to the parent.

id, user_id, comment_id__parent, comment_id__child, comment, created_dt

SQL Fiddle here

Now my problem is that I would like to get all comments of a specific user but only the latest update of a comment.

This is giving me a huge headache for a while and I would appreciate very much your input!

Strawberry
  • 33,750
  • 13
  • 40
  • 57
n00b
  • 16,088
  • 21
  • 56
  • 72

4 Answers4

2

If your fiddle is correct, you should be able to do this:

SELECT * FROM comments 
 WHERE comment_id__child IS NULL AND user_id=1;

This works if you always populate the comment_id__child for 'parent' comment when editing it.

vhu
  • 12,244
  • 11
  • 38
  • 48
0

for uer_id =1

select * from comments where user_id=1 order by created_dt desc;
Ronak Shah
  • 1,539
  • 2
  • 13
  • 20
0

This works perfectly! You can see the result in your sql fiddle.

select * from comments group by user_id having count(id) = 1
UNION
select * from comments where user_id in (select user_id from comments group by user_id having count(id) > 1) and comment_id__child is null and comment_id__parent is not null;
Kanishk Dudeja
  • 1,201
  • 3
  • 17
  • 33
0

I think i found a solution:

SELECT *
FROM comments
WHERE user_id = 1
  AND ( (comment_id__parent IS NULL
         AND comment_id__child IS NULL)
       OR (comment_id__parent IS NOT NULL
           AND comment_id__child IS NULL) )
ORDER BY created_dt DESC
n00b
  • 16,088
  • 21
  • 56
  • 72
  • This would only work for the user id 1. If you need to see the results for all users, you can check my comment. It works perfectly. – Kanishk Dudeja May 14 '14 at 13:32