2015-04-02 87 views
0

我需要新的列我的桌子產品新列 - >名爲Order(新列)。使用rails遷移,我需要添加新列並立即設置它的訂單號,但它需要由product_id完成。使該遞增通過它的順序

我的意思是我需要類似於:

product_id | order

1 ------------> 1 

1 ------------> 2 

1 ------------> 3 

2 ------------> 1 

2 ------------> 2 

有沒有辦法呢?

編輯: 您的SQL語法錯誤;檢查對應於你的MySQL服務器版本正確的語法使用近「」訂單」 = t1.'order'出現在第15行的手冊:

update product_submissions t 
     join (
     select 
     id, 
     product_id, 
     'order' from (
      select id, 
      product_id, 
      @rn:= if(@prev = product_id,@rn:[email protected]+1,1) as 'order', 
      @prev:=product_id 
      from product_submissions, 
      (select @rn:=0,@prev:=0)r 
      order by product_id,id 
     )x 
    )t1 on t1.id=t.id set t.'order' = t1.'order' 
+0

您需要添加的一些信息,請模式,例如訂單,產品及其關係,以及何時應設置上述數據等。 – 2015-04-02 12:56:18

+0

表中是否有任何主鍵? – 2015-04-02 12:58:23

+0

耶當然:ID – 2015-04-02 13:00:06

回答

0

考慮以下

mysql> create table test (id int ,product_id int); 
Query OK, 0 rows affected (0.14 sec) 

mysql> insert into test values (1,1),(2,1),(3,1),(4,2),(5,2); 

現在讓我們創建訂單

select 
product_id, 
`order` from ( 
    select 
    product_id, 
    @rn:= if(@prev = product_id,@rn:[email protected]+1,1) as `order`, 
    @prev:=product_id from test,(select @rn:=0,@prev:=0)r 
    order by product_id,id 
)x ; 

這會給你的東西作爲

+------------+-------+ 
| product_id | order | 
+------------+-------+ 
|   1 |  1 | 
|   1 |  2 | 
|   1 |  3 | 
|   2 |  1 | 
|   2 |  2 | 
+------------+-------+ 

現在,讓我們在更新命令使用,但在此之前,讓我們添加列(在你的情況下,它已經在那裏)

mysql> alter table test add column `order` int ; 
Query OK, 5 rows affected (0.29 sec) 

mysql> select * from test ; 
+------+------------+-------+ 
| id | product_id | order | 
+------+------------+-------+ 
| 1 |   1 | NULL | 
| 2 |   1 | NULL | 
| 3 |   1 | NULL | 
| 4 |   2 | NULL | 
| 5 |   2 | NULL | 
+------+------------+-------+ 
5 rows in set (0.00 sec) 

最後更新命令

update test t 
join (
select 
id, 
product_id, 
`order` from ( 
    select id, 
    product_id, 
    @rn:= if(@prev = product_id,@rn:[email protected]+1,1) as `order`, 
    @prev:=product_id 
    from test,(select @rn:=0,@prev:=0)r 
    order by product_id,id 
    )x 
)t1 on t1.id=t.id set t.`order` = t1.`order` 

mysql> select * from test ; 
+------+------------+-------+ 
| id | product_id | order | 
+------+------------+-------+ 
| 1 |   1 |  1 | 
| 2 |   1 |  2 | 
| 3 |   1 |  3 | 
| 4 |   2 |  1 | 
| 5 |   2 |  2 | 
+------+------------+-------+ 
5 rows in set (0.00 sec) 
+0

哇,很好。感謝您的回答:) – 2015-04-02 13:11:32

+0

以及它給了我錯誤:(錯誤味精在編輯的問題 – 2015-04-02 13:35:57

+0

它不是單引號''order''其backtics'' – 2015-04-02 13:42:12