2015-04-02 58 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