用多列mysql更新一个列值

时间:2012-11-21 11:59:35

标签: mysql codeigniter sql-update

我的数据库中有一张表。

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,请帮助。提前谢谢。

2 个答案:

答案 0 :(得分: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 FIDDLE DEMO

更新查询:

 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

答案 1 :(得分: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`;