I am making a nested comment system, and I have the following table:
create table comments (
id int unsigned primary key auto_increment,
author_id int unsigned not null,
target_id int unsigned not null,
target_type set('post','comment') not null,
content varchar(2000) not null
);
Each comment may be targeting a post, or another comment, in which case it would be considered a reply. Is there a simple way to count the number of nested comments (comments + replies + replies to replies, etc.) to a given post (say, a post with id 1)?
I know that if I had a field called target_post_id and another called target_comment_id, instead of having target_id and target_type, it would be very easy to count all the comments for any given post, but I have reasons for trying to keep this table structure, and truth be told, I’ve never dealt with recursive queries before. Any help is appreciated, thanks!!
The short answer is “no”. The slightly longer answer is that you could keep a comment count on the overall post, and update it as you add/delete comments in your nested structure (which is denormalising, but not entirely unexpected in this kind of situation); or as you point out you can always point back to the post from every comment.