简体   繁体   English

如何在 mysql 中创建一个随机的 4 位数字

[英]How do I create a random 4 digit number in mysql

I have a table of several hundred users and I want to create a 4-digit pin code like those used at an ATM machine for each user using an UPDATE statement.我有一个包含数百个用户的表,我想使用 UPDATE 语句为每个用户创建一个 4 位密码,就像在 ATM 机上使用的密码一样。 They don't have to be unique, but I don't want to use an autonumber type of field so one company cannot easily guess the pin code of another user.它们不必是唯一的,但我不想使用自动编号类型的字段,因此一家公司无法轻易猜出另一位用户的密码。 What is the simplest and easiest way to do this?最简单和最简单的方法是什么?

Note: This pin code is used as another layer of authentication, they also need a password to login.注意:此密码用作另一层身份验证,他们还需要密码才能登录。

From the Mysql docs ... 来自Mysql文档 ......

To obtain a random integer R in the range i <= R < j, use the expression FLOOR(i + RAND() * (j – i)). 为了获得范围i <= R <j的随机整数R,使用表达式FLOOR(i + RAND()*(j-i))。 For example, to obtain a random integer in the range the range 7 <= R < 12, you could use the following statement: 例如,要获取范围7 <= R <12的范围内的随机整数,可以使用以下语句:

SELECT FLOOR(7 + (RAND() * 5)); SELECT FLOOR(7 +(RAND()* 5));

update user set pin=(select floor(0+ RAND() * 10000)) where uid=<user_uid>;

Also I think you need to have the pin column be defined something like 另外我认为你需要定义类似的pin列

pin int(4) zerofill not null 

I would think. 我想。

Is there a reason why you can't just do 有没有理由不能做到

UPDATE `users` set `pin`=FLOOR(10000*RAND());

?

我认为类似于SUBSTRING(FLOOR(RAND()* 9999 + 10000),2)会做什么?

In my case I try to create random password for users ,here password is null就我而言,我尝试为用户创建随机密码,此处密码为空

update users set password =(FLOOR(RAND() * 9999) + 10000)  where password is null;

For your scenario对于您的场景

update users set pin =(FLOOR(RAND() * 9999) + 10000)  where pin is null;

This will help.这会有所帮助。

SELECT FLOOR ((RAND() * 10000));

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

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