2016-06-09 80 views
0

我有表product_to_store(它是opencart表),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  | 
+------------+----------+ 

謝謝大家提前爲您解答!

+0

你似乎沒有PRIMARY KEY。這在適當的時候可能會有問題。 – Strawberry

+0

@Strawberry我編輯了我的問題(alter table) – AlFra

回答

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 
) 
+0

我覺得這可能就是它。只需一秒鐘 – AlFra

+0

你能解釋每一行是什麼嗎? (因爲我幾乎總是新手) – AlFra

+0

這正是我所說的。如果你還有足夠的時間來解釋我會很感激。 – AlFra

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; 
/
+0

這對我來說太高級了。我是mysql中的noob:D – AlFra