使随机字符串不在数据库中 [英] Make Random String Not in Database

查看:52
本文介绍了使随机字符串不在数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写应用程序时,我想为数据库中的某些实体(例如ABCD)提供随机标签。这些总是四个字符,可以包含大写字母和数字。

While writing my application, I want to provide random tags to certain entities in my database, like ABCD for example. These are always four characters, can contain uppercase letters and numbers.

问题是,如何分配它们?我们将永远不会使用这种方法提供的160万种可能性,但是随着数据库变得更满,使用L4伪代码生成随机字符串的搜索时间将成倍增加:

The question is, how to assign them? We will never use the 1.6 million possibilities this provides, but as the database gets more full, the "seek" time for generating a random string using this L4 pseudo-code get exponentially longer:

function makeUniqueKey() {
    while (true) {
        $key = strtoupper(str_random(4));
        if (!DB::table('items')->where('key', '=', $key)->count()) {
            return $key;
        }
    }
}

我想这更多的是一个OCD好奇心问题,但是对于为数据库中的项创建随机,唯一键的非指数算法,有什么巧妙的窍门吗?

I suppose this is more of an OCD curiosity question, but is there any neat trick for a non-exponential algorithm in order to create random, unique keys for items in database?

推荐答案

最好不要随机分配它们。最简单的方法是增量操作(例如:从aaaa开始,一直到ZZZZ)。

Best would be to not assign them randomly. Simplest would be incremental, (e.g.: start at aaaa, all the way up to ZZZZ).

无论如何,我都将此字符串映射为一个数字。 aaaa = 1 ZZZZ = 52 ^ 4

Regardless I would map this string to a number. aaaa = 1, ZZZZ = 52^4.

您可以选择一个随机数,然后在数据库中搜索第一个缺口。应该可以与存储过程一起使用。这应该使性能下降至少是线性的,而不是随着数据集的增加呈指数下降。

You could then pick a random number, and then search the database for the first gap. Should be doable with stored procedures. This should make the performance decrease at least linear, not exponential as the dataset increases.

这篇关于使随机字符串不在数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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