I have an app set up which has nested comments attached to posts. I decided to use the closure table method (slide 40) for the comments due to how cheap hard disk space is versus how easy it seems to be to query and manage the tree structure. However, I'm running into a problem. I can't seem to figure out how to grab the tree path based on the post ID, not the ancestor ID (slide 49).
My database structure looks like this:
table: comment_paths
--------------------
parent_id (fk on comments.id)
child_id (fk on comments.id)
depth
table: comments
---------------
id
parent_id (fk on comments.id)
post_id (fk on posts.id)
text
table: posts
---------------
id
name
If I know the parent_id beforehand, as in the slideshow, it's simple to grab the tree:
SELECT c.*, p.*
FROM comments AS c
JOIN comment_paths AS p
ON c.id = p.child_id
WHERE p.parent_id = 1
However, I don't know the parent_id
beforehand; I only know the post_id
. The way the database is set up, there is more than one tree associated with a post:
[post]
-----------------------------------------
[comment] [comment] [comment] depth: 0
| |
[reply] [reply] depth: 1
| |
[r] [r] depth: 2
My initial solution was a query like this:
SELECT c.*, p.*
FROM comments AS c
JOIN comment_paths AS p
ON c.id = p.child_id
WHERE p.parent_id IN
(SELECT id FROM comments WHERE parent_id IS NULL AND post_id = 6)
It returns the correct data, but I feel like a nested SELECT like that isn't correct. Is there a better way to do this?
Thanks!
SELECT c.*, p.* FROM comments AS c JOIN comment_paths AS p ON c.id = p.parent_id WHERE c.parent_id IS NULL AND c.post_id = 6
– Heartland