Question

I have the following sql statement:

SELECT e.comment_id AS parentcomment,
m.comment_id AS child_id
FROM comments e
INNER JOIN comments m
ON e.comment_id=m.parent_id
WHERE e.parent='1' AND e.parent_id='$parentid' AND m.parent='0';

Sample output:

+---------------+----------+
| parentcomment | child_id |
+---------------+----------+
|             1 |        3 |
|             1 |        4 |
|             1 |        7 |
|             5 |        8 |
|             1 |        9 |
|             1 |       10 |
|             1 |       11 |
|             1 |       12 |
|             1 |       13 |
|             1 |       14 |
|             1 |       15 |
|             1 |       16 |
|             1 |       17 |
|             1 |       18 |
|             1 |       19 |
|             1 |       20 |
|             1 |       21 |
|             1 |       22 |
|             1 |       23 |
|             1 |       24 |
|             1 |       25 |
|            26 |       32 |
|            26 |       33 |
|            27 |       34 |
|            27 |       35 |
|            28 |       36 |
|            29 |       37 |
|            30 |       38 |
|            31 |       39 |
|            26 |       40 |
+---------------+----------+
30 rows in set

What I want to do - I only want to show 15 child_id values for each parentcomment value. In addition to that, I only want 30 parentcomment values to be retrieved.

MOREOVER, I want to ORDER the parentcomment values by a certain index (let's say id) and pick out only the top 30, and then pick out the top 15 out of the ordered child_id values (also ordered by id).

Hope this makes sense. How do I do those things?

Thanks in advance.

Was it helpful?

Solution

you should be able to work with this (sqlFiddle) here i am only grabbing 3 (instead of 15) child_id and 6 (instead of 30) parentcomment

and in my example, the $parentid is 1. The inner most query is your original query just added the ORDER BY parentcomment,child_id

SELECT parentcomment,child_id,parentRank,childRank
FROM
    (SELECT parentcomment,
           child_id,
           IF (@prevparent <> parentcomment, @parentRank:=@parentRank+1, @parentRank) as parentRank,
           IF (@prevparent <> parentcomment, @childRank:=1, @childRank:=@childRank+1) as childRank,
           @prevparent := parentcomment
     FROM
       (SELECT e.comment_id AS parentcomment,
               m.comment_id AS child_id
        FROM comments e
        INNER JOIN comments m
        ON e.comment_id=m.parent_id
        WHERE e.parent='1' AND e.parent_id='1' AND m.parent='0'

          ORDER BY parentcomment,child_id
       )T1,
       (SELECT @prevparent:=0,@parentRank:=0,@childRank:=0)rank
     )T2
WHERE parentRank BETWEEN 1 AND 6
AND   childRank BETWEEN 1 AND 3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top