mysqlsql-updateparent-childdistinct-valuesdenormalized

Accumulate unique values for parent records using delimited child record values in a denormalized table


I have a table in my database.

ShopID | ParentID | SELL 

1          0        2,3
2          1        1,2,3
3          1        2,3,4
4          0        5,6
5          4        5,6,7
6          4        6,7,8

I want to add the children SELL values to the parent shop's SELL values, but don't want to add duplicate values.

Ultimately, I want to have a table like this:

ShopID | ParentID | SELL 

1          0        1,2,3,4
2          1        1,3
3          1        2,4
4          0        5,6,7,8
5          4        5,7
6          4        6,8

Is this possible with MySQL?


Solution

  • try this:

    SELECT s1.shopid, s1.parentid, IFNULL( s2.sales, s1.SELL ) SELL
    FROM shop s1
    LEFT JOIN (
      SELECT parentid, GROUP_CONCAT( sell ) sales
      FROM shop
      GROUP BY parentid
    )s2 ON s1.ShopId = s2.parentid;
    

    SQL FIDDLE DEMO

    Update Query:

     update shop
        SET SELL=s.SELL 
        from shop join (select s1.shopid,s1.parentid,ifnull(s2.sales,s1.SELL) SELL from shop s1 left join 
        (select parentid,group_concat(sell) sales from shop
        group by parentid) s2
        on s1.ShopId=s2.parentid) s
        on shop.shopid = s.shopid