Select Parent and Children With MySQL

后端 未结 3 1403
后悔当初
后悔当初 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;
    

提交回复
热议问题