考慮以下
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