简体   繁体   English

如何使用唯一的随机序列号更新MySQL表列?

[英]How to update my MySQL table column with unique random sequence number?

I try to update my MySQL table column, and set random sequence number, begin from 1,2,3,etc. 我尝试更新我的MySQL表列,并设置随机序号,从1,2,3等开始。 For example, I have total 38 row, so i need update it with number 1-38 (can't duplicate). 例如,我总共有38行,所以我需要用数字1-38更新它(不能重复)。 i tried using: 我尝试使用:

UPDATE TABLE SET VALUE=FLOOR(RAND()*38)+1

but it gives me some duplicate number, i need every rows have different number. 但这给了我一些重复的数字,我需要每一行都有不同的数字。

You can try something like this: 您可以尝试如下操作:

SET @r := 0;
UPDATE  table
SET     value = (@r := @r + 1)
ORDER BY
        RAND();

This will assign numbers 1 to 38 would be assigned randomly and uniquely. 这将分配1到38的数字,这些数字将随机且唯一地分配。

SQLFiddle SQLFiddle

Hope this helps!!! 希望这可以帮助!!!

Might not be exactly what you want, but if you are looking towards assigning unique ID starting from 1 to your table, architectally good solution would be making your 'id' column an auto incrementing unique number: 可能不完全是您想要的,但是如果您希望为表分配从1开始的唯一ID,那么架构上好的解决方案就是将“ id”列设为自动递增的唯一编号:

ALTER TABLE TABLE_NAME ADD COLUMN_NAME INT PRIMARY KEY AUTO_INCREMENT;

If you already have the column, you could previously remove it: 如果您已经有了该列,则可以先前将其删除:

ALTER TABLE TABLE_NAME DROP COLUMN_NAME
  • Step 1 : Do a for loop and store all 38 numbers in an array. 步骤1:执行for循环并将所有38个数字存储在数组中。
  • Step 2 : shuffle that array using shuffle function. 步骤2:使用随机播放功能对数组进行随机播放。 http://php.net/manual/en/function.shuffle.php http://php.net/manual/en/function.shuffle.php
  • Step 3 : Do a Foreach loop for that shuffled array and update your column. 步骤3:对该改组后的数组执行Foreach循环并更新您的列。

Just example code: 只是示例代码:

  for($i=1;$i<=38;$i++)
  {
     $arr[$i] = $i;
  }

  shuffle($arr);

  foreach($arr as $randarray)
  {
     //Your SQL query here UPDATE TABLE SET VALUE=$randarray like that
  }

If you want a solution only in MySQL you need something like this: 如果仅在MySQL中需要解决方案,则需要这样的内容:

update test set id =  (select MAX(id)+1 from test)  WHERE <your_condition>

But you will get error: 但是你会得到错误:

You can't specify target table 'test' for update in FROM clause

So you have to do something like that to avoid this error: 因此,您必须执行类似的操作以避免此错误:

    update test set 
    id =  ( 
     select maxPlus1 from 
      (
       select MAX(id)+1 as maxPlus1 
       from test
      ) 
      maxTable
     ) WHERE <your_condition>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM