Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

for uer_id =1

select * from comments where user_id=1 order by created_dt desc;

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;

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top