2

So I took accepted answer here Select Parent and Children With MySQL for my submissions_comments schema which looks like:

+---------------+------------------+------+-----+---------+----------------+
| Field         | Type             | Null | Key | Default | Extra          |
+---------------+------------------+------+-----+---------+----------------+
| id            | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| user_id       | int(10) unsigned | NO   | MUL | NULL    |                |
| submission_id | int(11)          | NO   | MUL | NULL    |                |
| comment       | text             | NO   |     | NULL    |                |
| parent_id     | int(10) unsigned | YES  | MUL | NULL    |                |
| created       | datetime         | NO   | MUL | NULL    |                |
| created_ip    | int(11)          | NO   |     | NULL    |                |
| helpful_count | int(11)          | NO   | MUL | NULL    |                |
| deleted       | tinyint(4)       | NO   | MUL | 0       |                |
+---------------+------------------+------+-----+---------+----------------+'

as

  SELECT *
    FROM submissions_comments AS parent
         LEFT JOIN submissions_comments AS child 
         ON child.parent_id = parent.id
   WHERE parent.parent_id IS NULL
ORDER BY parent.id, child.id;

And I ended up with the following results:

+----+---------+---------------+-------------------------------+-----------+---------------------+------------+---------------+---------+------+---------+---------------+--------------------------------+-----------+---------------------+------------+---------------+---------+
| id | user_id | submission_id | comment                       | parent_id | created             | created_ip | helpful_count | deleted | id   | user_id | submission_id | comment                        | parent_id | created             | created_ip | helpful_count | deleted |
+----+---------+---------------+-------------------------------+-----------+---------------------+------------+---------------+---------+------+---------+---------------+--------------------------------+-----------+---------------------+------------+---------------+---------+
|  1 |      15 |            23 | This is a parent              |      NULL | 2014-02-19 01:41:39 |     127001 |             0 |       0 |    2 |      15 |            23 | This is a child comment        |         1 | 2014-02-19 01:41:43 |     127001 |             0 |       0 |
|  1 |      15 |            23 | This is a parent              |      NULL | 2014-02-19 01:41:39 |     127001 |             0 |       0 |    4 |      15 |            23 | This is a second child comment |         1 | 2014-02-19 02:01:29 |     127001 |             0 |       0 |
|  3 |      15 |            23 | I don't have any children |      NULL | 2014-02-19 01:43:30 |     127001 |             0 |       0 | NULL |    NULL |          NULL | NULL                           |      NULL | NULL                |       NULL |          NULL |    NULL |
+----+---------+---------------+-------------------------------+-----------+---------------------+------------+---------------+---------+------+---------+---------------+--------------------------------+-----------+---------------------+------------+---------------+---------+

As you can see, the first two rows in the results contain the parent comment with the child comments joined. Is there a way with MySQL to cleanly nest all child comments within one parent comment that is returned or do I need to use something like underscore's _.pluck method on my returned results object?

1
  • 2
    What do you mean by "cleanly nest all child comments within one parent comment"? Could you put an example of the desired result?
    – Rafa Paez
    Feb 21, 2014 at 17:14

4 Answers 4

3
+50

Is this what you mean?

SELECT parent.id, MAX(parent.comment) as pcomm,
       GROUP_CONCAT(child.id ORDER BY child.id) as siblings,
       GROUP_CONCAT(child.comment ORDER BY child.id) as siblingComments
FROM   submissions_comments AS parent
 LEFT  JOIN submissions_comments AS child
   ON  child.parent_id = parent.id
WHERE  parent.parent_id IS NULL
GROUP  BY parent.id
ORDER  BY parent.id;

I'm assuming that by "nesting" you just mean you want the sibling results grouped together somehow.

6
  • Interesting. This certainly works, but how efficient (or inefficient) would this be from a performance standpoint? Also when paging comes into account (assuming I'm fetching only 10 at a time).
    – bob_cobb
    Feb 22, 2014 at 4:02
  • The problem with GROUP_CONCAT is that not only so I need to separate them by some ascii character and then split them later, it leaves out the meta data for each sibling comment (time, user_id, etc).
    – bob_cobb
    Feb 22, 2014 at 20:11
  • You can GROUP CONCAT those other fields as well (using the same ORDER BY to make sure they still match up). Or you can concatenate them together prior to the GROUP_CONCAT, then split them up in the code. Problem comes when you use a separator that someone has used in a comment.
    – Kickstart
    Feb 25, 2014 at 10:24
  • If I want to join on users u for the parent and children so I can get the parent.username, child.username, I'd do a LEFT JOIN users u on parent.user_id = u.id but it doesn't seem to be working. Getting unknown column child.username in field list. Thoughts?
    – bob_cobb
    Feb 27, 2014 at 21:11
  • @bob_cobb Sorry I was not online to answer your queries about my answer. Perhaps make another new question for your new issue? It's hard to diagnose in Comments section.
    – dg99
    Feb 28, 2014 at 19:12
1

Edit - Try this to see if you like it, otherwise skip forward to another group_concat idea -

The following approach will show all column values for each parent only on the first row where there is a child comment (or none). On rows that show a 2nd, 3rd, etc. child comment, the values for the parent will all be blank, and only the sibling data will be shown on the right. This gives you a quick visual as to where one comment (parent) ends and where another (along with another sequence of siblings) begin.

SELECT case when parent.id = child_min_id then parent.id else null end as id,
       case when parent.id = child_min_id then child.parent.user_id else null end as user_id,
       case when parent.id = child_min_id then parent.submission_id else null end as submission_id,
       case when parent.id = child_min_id then parent.comment else null end as comment,
       case when parent.id = child_min_id then parent.parent_id else null end as parent_id,
       case when parent.id = child_min_id then parent.created else null end as created,
       case when parent.id = child_min_id then parent.created_ip else null end as created_ip,
       case when parent.id = child_min_id then parent.helpful_count else null end as helpful_count,
       case when parent.id = child_min_id then parent.deleted else null end as deleted,
       child.*
  FROM submissions_comments AS parent
  LEFT JOIN submissions_comments AS child
    ON child.parent_id = parent.id
  left join submissions_comments as child_min
    on child.id = child_min.id
 WHERE parent.parent_id IS NULL
   and (child_min.id =
       (select min(x.id)
           from submissions_comments x
          where x.parent_id = child.parent_id) or child_min.id is null)
 ORDER BY parent.id, child.id;

Below is an edit of the above in answer to how I would approach joining into the users table for both parent/children, and how to display relevant columns from each. Note that because I'm not sure what columns you want selected, I just grabbed a column called "relevantcolumn" for both parent/child (change in your version):

SELECT case when parent.id = child_min_id then parent.id else null end as id,
       case when parent.id = child_min_id then child.parent.user_id else null end as user_id,
       case when parent.id = child_min_id then parent.submission_id else null end as submission_id,
       case when parent.id = child_min_id then parent.comment else null end as comment,
       case when parent.id = child_min_id then parent.parent_id else null end as parent_id,
       case when parent.id = child_min_id then parent.created else null end as created,
       case when parent.id = child_min_id then parent.created_ip else null end as created_ip,
       case when parent.id = child_min_id then parent.helpful_count else null end as helpful_count,
       case when parent.id = child_min_id then parent.deleted else null end as deleted,
       case when u_par.id = child_min_id then u_par.relevant_column else null end as usertblcolumn,
       child.*,
       u.relevantcolumn as usertblcolumnforchild
  FROM submissions_comments AS parent
  LEFT JOIN submissions_comments AS child
    ON child.parent_id = parent.id
  left join submissions_comments as child_min
    on child.id = child_min.id
  left join users as u
    on child.id = u.id
  left join users as u_par
    on parent.id = u_par.id
 WHERE parent.parent_id IS NULL
   and (child_min.id =
       (select min(x.id)
           from submissions_comments x
          where x.parent_id = child.parent_id) or child_min.id is null)
 ORDER BY parent.id, child.id;

Group concat approach:

Regarding your comment about wanting the meta data, you can use group_concat and concat together to both aggregate vertically and horizontally at the same time, like this:

SELECT parent.id,
       MAX(parent.comment) as pcomm,
       GROUP_CONCAT(concat(child.id,', ',child.user_id,', ',child.created,', ',child.comment) ORDER BY child.id) as siblings
  FROM submissions_comments AS parent
  LEFT JOIN submissions_comments AS child
    ON child.parent_id = parent.id
 WHERE parent.parent_id IS NULL
 GROUP BY parent.id
 ORDER BY parent.id;

You still have to split them into separate columns later if that's what you want, but the other fields will be there side by side.

You can also use literals to help distinguish, if it makes it any easier to read:

SELECT parent.id,
       MAX(parent.comment) as pcomm,
       GROUP_CONCAT(concat('Child ID ',
                           ', ',
                           child.id,
                           ', ',
                           'Child User ID ',
                           ', ',
                           child.user_id,
                           ', ',
                           'Child Date ',
                           ', ',
                           child.created,
                           ', ',
                           'Child Comment ',
                           child.comment) ORDER BY child.id) as siblings
  FROM submissions_comments AS parent
  LEFT JOIN submissions_comments AS child
    ON child.parent_id = parent.id
 WHERE parent.parent_id IS NULL
 GROUP BY parent.id
 ORDER BY parent.id;
3
  • Wow very comprehensive on helping me wrap my brain around this. The only concern I have is that I'll still need to do some parsing for each sibling comment and then push those into an array (then append that as an object to the parent comment object). I guess this is the way to go (especially with paging because each parent comment needs to have all of its children). One problem I have though is that I still need to join child.id on users u where child.is = u.id along with for the parent comments. How would you approach that (you can see how this is getting pretty sloppy)?
    – bob_cobb
    Feb 24, 2014 at 4:10
  • @bob_cobb I would add another left join (left join users u on child.id = u.id) and add whatever columns from the users table that you want selected to the select list. You would do the same for the user table's columns for the parent id (left join users u_par on parent.id = u_par.id) (note I used a 2nd alias for users for parents). Then follow the same approach for bringing back those columns as I did with the other parent columns (make them null if a 2nd row, using the case when column is min, show it, otherwise show null). Feb 26, 2014 at 4:07
  • Doing this, I get unknown column child.username in field list: pastebin.com/raw.php?i=uiYQZVRq I also want to fetch the parents username after joining as well.
    – bob_cobb
    Feb 27, 2014 at 7:17
0

I've not saying exactly, i think your getting this kind of problem as following as:

Ordered_Item

ID | Item_Name
1  | Pizza
2  | Stromboli

Ordered_Options

Ordered_Item_ID | Option_Number | Value
        1               43         Pepperoni
        1               44         Extra Cheese
        2               44         Extra Cheese

Output

ID | Item_Name | Option_1 | Option_2
1    Pizza       Pepperoni  Extra Cheese
2    Stromboli     NULL     Extra Cheese

And the my suggestions to use this method resolve this problem as there following as:

The easiest way would be to make use of the GROUP_CONCAT group function here..

select ordered_item.id as Id, ordered_item.Item_Name as ItemName,

GROUP_CONCAT(Ordered_Options.Value) as Options

from ordered_item, ordered_options

where ordered_item.id=ordered_options.ordered_item_id

group by ordered_item.id

Which would output:

Id              ItemName       Options
1               Pizza          Pepperoni,Extra Cheese
2               Stromboli      Extra Cheese

That way you can have as many options as you want without having to modify your query.

Ah, if you see your results getting cropped, you can increase the size limit of GROUP_CONCAT like this:

SET SESSION group_concat_max_len = 8192;
0

If you want to show all child comment inside one column in the parent row, you need to use a function to archive this.

Here is an example:

CREATE DEFINER = 'root'@'localhost' FUNCTION `getChildComments`(p_parent_id INTEGER(11))
    RETURNS varchar(4000) 
    DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT ''
begin
declare v_comments, v_return varchar(4000);
DECLARE done INT DEFAULT 0;
DECLARE cur1 CURSOR FOR
        select comment
          from submissions_comments t
            where parent_id=p_parent_id;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;
set v_return='';
OPEN cur1;
  REPEAT
  FETCH cur1 INTO v_comments;
   IF NOT done THEN
      if (v_return='') then
            set v_return=v_comments;
      else
            set v_return=concat(v_return,';',v_comments);
      end if;
   end if;
  UNTIL done END REPEAT;
  CLOSE cur1;
return v_return;
end;

Then :

SELECT parent_id, getChildComments(parent_id) from (
SELECT distinct parent_id as prarent_id from submissions_comments ) x ;

Make sure you have an index on parent_id column ;)

P.S.: I use a VARCHAR in above function but I think it should work for TEXT too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.