复制表行,但使用其他值

时间:2016-06-09 14:10:50

标签: mysql sql database mysqli

我有表product_to_storeopencart表),product_idstore_id作为列标题。表中填充了数据(示例如下):

+------------+----------+
| product_id | store_id |
+------------+----------+
| 123        | 0        |
| 124        | 0        |
| 125        | 0        |
| 126        | 0        |
| 125        | 1        |
+------------+----------+

帮助(来自mysql表转储):

CREATE TABLE `product_to_store` (
  `product_id` int(11) NOT NULL,
  `store_id` int(11) NOT NULL DEFAULT '0'
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `product_to_store` (`product_id`, `store_id`) VALUES
(123, 0),
(124, 0),
(125, 0),
(126, 0),
(125, 1);

ALTER TABLE `product_to_store`
  ADD PRIMARY KEY (`product_id`,`store_id`);

我想将值为0的所有行复制为store_id。而不是值0,我希望它们具有值1(例如)。我怎么能用mysql语法呢?

所以决赛桌看起来应该是这样的

+------------+----------+
| product_id | store_id |
+------------+----------+
| 123        | 0        |
| 124        | 0        |
| 125        | 0        |
| 126        | 0        |
| 125        | 1        |
| 123        | 1        |
| 124        | 1        |
| 126        | 1        |
+------------+----------+

提前感谢大家的答案!

2 个答案:

答案 0 :(得分:1)

我认为这会对你有所帮助:

insert ignore into `product_to_store` (
  select a.product_id, 1 as store_id
  from (select distinct product_id from product_to_store where store_id=0) a
)

答案 1 :(得分:0)

您可以制作光标以检索您要查找的记录。
循环遍历该游标并将这些行放在记录中,以便您可以修改它们。
这样你就可以对每一行做点什么。

例如:

DECLARE
    CURSOR cHelloWorld IS 
            SELECT  product_id, 
                    store_id 
                FROM    product_to_store 
                WHERE   store_id = 0; 

    rHelloWorld     cHelloWorld%ROWTYPE;

BEGIN
        --Loop through records from cursor. 
        OPEN cHelloWorld;
        LOOP
                FETCH cHelloWorld INTO rHelloWorld;
                -- Exit loop when all lines have been looked through.
                EXIT WHEN cHelloWorld%NOTFOUND;

        INSERT INTO product_to_store(product_id, store_id)
                VALUES (rHelloWorld.product_id, 1); 
        END LOOP;
        CLOSE cHelloWorld;

        COMMIT;
END;
/