mysql with 生成序列_使用MySQL生成唯一且随机的代码数字

bd96500e110b49cbb3cd949968f18be7.png

Initial goal:

I would like to generate random and unique codes (6 digits) in a table.

I use a SQL query like this one to do that:

SELECT SUBSTRING(CRC32(RAND()), 1, 6) as myCode

FROM `codes`

HAVING myCode NOT IN (SELECT code FROM `codes`)

I asked me about how it will react when there will be no more available codes so I do the following test

Test context:

MySQL version: 5.5.20

MySQL Table:

CREATE TABLE `codes` (

`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,

`code` VARCHAR( 10 ) NOT NULL ,

UNIQUE (

`code`

)

) ENGINE = InnoDB;

Initial data:

INSERT INTO `codes` (`id`, `code`)

VALUES (NULL, '1'), (NULL, '2'), (NULL, '3'), (NULL, '4'), (NULL, '5'), (NULL, '6'), (NULL, '7'), (NULL, '8');

SQL Query:

SELECT SUBSTRING(CRC32(RAND()), 1, 1) as myCode

FROM `codes`

HAVING myCode NOT IN (SELECT code FROM `codes`)

By execute this query, I expect that it will always return 9 because it is the only code of one digit which does not exists.

But the result is:

Sometime it return any rows

Sometime it return rows with values that already exists

I don't understand this behavior so if someone can help :)

So the big question is:

How MySQL can return rows with values that already exists?

Thanks

解决方案

I would fill a sequencetable table with all the possible values, in sequence.

Then the random query just randomly selects records from the sequencetable, and each time it picks a record it deletes it. This way you will surely get all the numbers, without wasting time in finding a "hole" number (not already picked up).

CREATE TABLE `sequencetable`

(

`sequence` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,

PRIMARY KEY (`sequence`)

)

ENGINE=InnoDB

AUTO_INCREMENT=1;

Fill the sequence (no need for the AUTOINCREMENT actually).

DECLARE i INT;

SET i=1;

REPEAT

INSERT INTO sequencetable VALUES (i);

SET i=i+1;

UNTIL i>999999 END REPEAT;

Select a random record from the sequence (do this in a loop until records are available):

DECLARE sequencen INT;

SET sequencen =

(SELECT sequence FROM sequencetable ORDER BY RAND() LIMIT 1);

DELETE FROM sequencetable WHERE sequence = sequencen;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值