如何混合列数据

时间:2019-04-17 14:05:51

标签: mysql sql sql-update

我有一张桌子table_1

 id     contact_id
 1         500
 5         89
 8         35
 15        458
 ...       ...
 555       38

如何混合contact_idtable_1的结果

id     contact_id
 1         35
 5         458
 8         35
 15        89
 ...       ...
 555       45

1 个答案:

答案 0 :(得分:1)

您可以使用变量或row_number()(在MySQL 8+中)随机分配联系人ID:

select t1.id, tt1.contact_id
from (select t1.*, row_number() over (order by id) as seqnum
      from table_1 t1
     ) t1 join
     (select t1.*, row_number() over (order by rand()) as seqnum
      from table_1 t1
     ) tt1
     on t1.seqnum = tt1.seqnum;

没有很多困难(但输入更多),可以将其转换为使用早期版本中的变量。

如果您想永久地改组值,也可以将其合并到update语句中。

编辑:

我想你想要

update table1 t1 join
       (select t1.id, tt1.contact_id
        from (select t1.*, (@rn1 := @rn1 + 1) as seqnum
              from (select * table_1 order by id) t1 cross join
                   (select @rn1 := 0) params
             ) t1 join
             (select t1.*, (@rn2 := @rn2 + 1) as seqnum
              from (select * from table_1 order by rand()) t1 cross join
                   (select @rn2 := 0) params
             ) tt1
             on t1.seqnum = tt1.seqnum
       ) tt1
       on tt1.id = t1.id
    set t1.contact_id = tt1.contact_id;