1

嗨,我的数据库中有一张表。

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

我想将子 SELL值添加到父商店的SELL值中,但不想添加重复值,

最后我想要一张这样的桌子

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

这可能吗MySQL,请帮忙。提前致谢 。

4

2 回答 2

2

试试这个:

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 小提琴演示

更新查询:

 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
于 2012-11-21T12:35:09.940 回答
1

我建议您创建一个新列。

像 :

ShopID | ParentID | SELL | Total Sell

但最好的方法是为每条记录存储一个值,例如:

ShopID | ParentID | SELL 

1          0        2
1          0        3

比您能够轻松地操纵数据...

CREATE TABLE IF NOT EXISTS `sellforce` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ShopID` int(11) NOT NULL,
  `ParentID` int(11) NOT NULL,
  `Sell` int(11) NOT NULL,
  PRIMARY KEY (`id`)
)

INSERT INTO `sellforce` (`ShopID`, `ParentID`, `Sell`) VALUES
( 1, 0, 2),
( 2, 1, 1),
( 1, 0, 3),
( 2, 1, 3);

CREATE VIEW `sellforce1` AS select `sellforce`.`ShopID` AS `ShopID`,`sellforce`.`ParentID` AS `ParentID`,group_concat(distinct `sellforce`.`Sell` separator ',') AS `GROUP_CONCAT( DISTINCT ``Sell`` )` from `sellforce` group by `sellforce`.`ShopID`;
于 2012-11-21T12:11:31.050 回答