I have a simple table like this:
+------------+---------+-----------+--------------+
| comment_id | post_id | parent_id | comment_text |
+------------+---------+-----------+--------------+
| 1 | 200 | 0 | a |
| 2 | 200 | 0 | b |
| 3 | 200 | 1 | c |
| 4 | 200 | 1 | d |
| 5 | 200 | 0 | e |
| 6 | 200 | 2 | f |
| 7 | 200 | 2 | g |
| 8 | 200 | 0 | h |
| 9 | 200 | 0 | i |
| 10 | 200 | 1 | k |
+------------+---------+-----------+--------------+
Column parent_id tells us that this comment is a reply to another comment with this id.
Let's say there is only one level nesting of comments.
Now I need to return only first 5 parent comments and all of the children that belong to them.
I have a query for that but there is one problem.
(
SELECT c.*
FROM comments AS c
WHERE c.post_id = '200' AND parent_id='0'
LIMIT 0,5
)
UNION
(
SELECT c.*
FROM comments AS c
WHERE c.post_id = '200' AND c.parent_id IN
(
SELECT c.comment_id
FROM comments AS c
WHERE c.post_id= '200' AND parent_id='0'
LIMIT 0,5
)
)
The problem is that my current mySQL version doesn't support LIMIT in sub-queries. Also it seems that I execute same SELECT query twice!
I'm sure there must be a way to do this more elegantly.