mysql排序字段增加值与额外分组

时间:2019-01-17 07:15:40

标签: php mysql

我已损坏了sort_order字段,需要通过将行更新为递增顺序来更正该字段。如果没有分组,此解决方案将非常有用:

SET @i := 0;
UPDATE tbl SET sort_order= @i:=@i+1 ORDER BY sort_order;

但是,当您谈论的表需要为每个组重置sort_order字段时,该解决方案将失败。就我而言,唯一组是用户和类型的组合,因此应该为每个唯一用户/类型组合重新设置sort_order。

该怎么做才能更新此信息?

id      user    type    name    sort_order
152070  cust    forex   ^EURUSD 3
374143  cust    forex   ^EURGBP 3
376218  cust    stock   IBM     3
376219  cust    stock   FB      3
376219  cust    stock   AMZN    3
374676  degr    forex   ^BTCUSD 3
376217  degr    forex   ^AUDJPY 3
376220  degr    stock   C       3
376221  degr    stock   AMZN    3

看起来像这样:

id      user    type    name    sort_order
152070  cust    forex   ^EURUSD 1
374143  cust    forex   ^EURGBP 2
376218  cust    stock   IBM     1
376219  cust    stock   FB      2
376219  cust    stock   AMZN    3
374676  degr    forex   ^BTCUSD 1
376217  degr    forex   ^AUDJPY 2
376220  degr    stock   C       1
376221  degr    stock   AMZN    2

我也愿意接受PHP解决方案。

编辑:

MySql 5.6

我发布的第一个解决方案导致了这个结果,这不是期望的结果。同样,我想按组重新排序。

id      user    type    name    sort_order
152070  cust    forex   ^EURUSD 1
374143  cust    forex   ^EURGBP 2
376218  cust    stock   IBM     3
376219  cust    stock   FB      4
376219  cust    stock   AMZN    5
374676  degr    forex   ^BTCUSD 6
376217  degr    forex   ^AUDJPY 7
376220  degr    stock   C       8
376221  degr    stock   AMZN    9

1 个答案:

答案 0 :(得分:1)

此站点上有很多关于行号模拟的答案,这是用于多表更新的另一个答案。

drop table if exists t;
create table t
(id  int ,   user varchar(20) ,  type varchar(20) ,  name varchar(20),   sort_order int);
insert into t values
(152070 , 'cust'  ,  'forex' ,  '^EURUSD' ,3),
(374143 , 'cust'  ,  'forex' ,  '^EURGBP' ,3),
(376218 , 'cust'  ,  'stock' ,  'IBM'     ,3),
(376219 , 'cust'  ,  'stock' ,  'FB'      ,3),
(376219 , 'cust'  ,  'stock' ,  'AMZN'    ,3),
(374676 , 'degr'  ,  'forex' ,  '^BTCUSD' ,3),
(376217 , 'degr'  ,  'forex' ,  '^AUDJPY' ,3),
(376220 , 'degr'  ,  'stock' ,  'C'       ,3),
(376221 , 'degr'  ,  'stock' ,  'AMZN'    ,3);

update t join
(select t.*,
        if(concat(user,type) <> @p, @rn:=1,@rn:=@rn+1) rownumber,
        @p:= concat(user,type) p
from t
cross join (select @rn:=0,@p:='') r
order by user,type,id) s
on s.id = t.id
set t.sort_order = s.rownumber
;
select * from t;

--------+------+-------+---------+------------+
| id     | user | type  | name    | sort_order |
+--------+------+-------+---------+------------+
| 152070 | cust | forex | ^EURUSD |          1 |
| 374143 | cust | forex | ^EURGBP |          2 |
| 376218 | cust | stock | IBM     |          1 |
| 376219 | cust | stock | FB      |          3 |
| 376219 | cust | stock | AMZN    |          3 |
| 374676 | degr | forex | ^BTCUSD |          1 |
| 376217 | degr | forex | ^AUDJPY |          2 |
| 376220 | degr | stock | C       |          1 |
| 376221 | degr | stock | AMZN    |          2 |
+--------+------+-------+---------+------------+