考虑以下
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)
您需要添加的一些信息,请模式,例如订单,产品及其关系,以及何时应设置上述数据等。 – 2015-04-02 12:56:18
表中是否有任何主键? – 2015-04-02 12:58:23
耶当然:ID – 2015-04-02 13:00:06