Select Parent and Children With MySQL

后端 未结 3 1385
后悔当初
后悔当初 2020-12-16 18:05

I know this question comes up often, but today I can\'t find the answer I\'m looking for. I have a table with this schema.

CREATE TABLE `comments` (
    `id`         


        
相关标签:
3条回答
  • 2020-12-16 18:18

    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:

    1. 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 讨论(0)
  • 2020-12-16 18:37

    Are you looking for

    SELECT p.id, child.*
    FROM comments p
    INNER JOIN comments child ON (child.parent_id = p.id)
    WHERE ....
    

    UPDATE
    Or LEFT JOIN if you want to see rows with no parents

    0 讨论(0)
  • 2020-12-16 18:39

    Parents are records with no parent_id.
    Children have parent_id equal to the parent comment's id.

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

    Note that the self-join should be an outer join so that you don't miss parent comments with no children.

    0 讨论(0)
提交回复
热议问题