产生连续的五位字母数字ID [英] generating an sequential five digit alphanumerical ID

查看:481
本文介绍了产生连续的五位字母数字ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

总体概述:

下面的函数吐出随机ID。我用这个来提供一个确认别名来确定一条记录。但是,我不得不检查冲突(但不太可能),因为我们只使用一个五位数的长度。随着允许的字符下面列出,它出来,以约33万美元,外加组合。最终,我们将得到五百万左右的记录,以便冲突成为一个问题。

的问题:

检查欺骗别名是效率低下,资源重。五百万条记录是很多进行搜索。特别是当这种搜索是由不同的用户同时进行。

我的问题:

有没有一种方法,以自动增量通过这个功能允许的组合?这意味着我只需要搜索的最后一个记录的别名,并移动到下一个组合?

确认的限制:

我实现了code会比下方的功能大不相同。我也意识到,MySQL已经用于数字ID的自动递增功能,但该项目需要五位别名23456789ABCDEFGHJKLMNPQRSTUVWXYZ所允许的字符。我的双手被缚在这个问题上。

我目前的功能:

 公共职能random_id_gen($长度)
 {
     $字符='23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
     $最大值=的strlen($字符) -  1;
     $字符串='';

     为($ i = 0; $ I< $长度; $ I ++){
         $串= $字符[mt_rand(0,$最大值)]。
     }

     返回$串;
 }
 

解决方案

为什么不只是创造上的别名列的唯一索引?

  CREATE UNIQUE INDEX uniq_alias mytable上(别名);
 

在这点你可以尽你插入/更新,如果它返回一个错误,产生一个新的别名,然后重试。

General Overview:

The function below spits out a random ID. I'm using this to provide a confirmation alias to identify a record. However, I've had to check for collision(however unlikely), because we are only using a five digit length. With the allowed characters listed below, it comes out to about 33 million plus combinations. Eventually we will get to five million or so records so collision becomes an issue.

The Problem:

Checking for dupe aliases is inefficient and resource heavy. Five million records is a lot to search through. Especially when this search is being conducted concurrently by different users.

My Question:

Is there a way to 'auto increment' the combinations allowed by this function? Meaning I only have to search for the last record's alias and move on to the next combination?

Acknowledged Limitations:

I realize the code would be vastly different than the function below. I also realize that mysql has an auto increment feature for numerical IDs, but the project is requiring a five digit alias with the allowed characters of '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'. My hands are tied on that issue.

My Current Function:

 public function random_id_gen($length)
 {
     $characters = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
     $max = strlen($characters) - 1;
     $string = '';

     for ($i = 0; $i < $length; $i++) {
         $string .= $characters[mt_rand(0, $max)];
     }

     return $string;
 }

解决方案

Why not just create a unique index on the alias column?

CREATE UNIQUE INDEX uniq_alias ON MyTable(alias);

at which point you can try your insert/update and if it returns an error, generate a new alias and try again.

这篇关于产生连续的五位字母数字ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆