[英]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. 但这给了我一些重复的数字,我需要每一行都有不同的数字。
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
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.