代码之家  ›  专栏  ›  技术社区  ›  Igor

生成不存在于同一列中的随机值

  •  1
  • Igor  · 技术社区  · 10 年前

    我已经在谷歌上搜索过了,但我刚刚找到了类似的答案。
    我不是后端开发人员,所以我对SQL不太了解。我需要生成并插入一个包含数字和字符(我想是varchar)的6位随机值,这些数字和字符不存在于同一列中。

    我试过这个 FLOOR(RAND() * 401) + 100 我在某个地方找到的,但它只是生成数字而已。

    我迷路了。

    数据库大师们,请用你们的随机数照亮我的路;-;

    2 回复  |  直到 10 年前
        1
  •  1
  •   Paul Spiegel    10 年前
    SELECT LPAD(CONV(RAND() * POW(36, 6), 10, 36), 6, 0)
    

    这将创建一个6个字符的“随机”字母数字值。

    但是:

    • 您需要检查该值是否已存在于表中。
    • 分布是不相等的,因为rand()返回的FLOAT的精度只有23位,而POW(36,6)需要32位。

    更新:

    然而,因为您需要检查,如果值已经存在,您最好在PHP中创建数字。

    $success = false;
    while (!$success) {
        $rndInt = rand(0, pow(36, 6) - 1);
        $rndStr = base_convert ($rndInt, 10, 36);
        $rndStr = str_pad($rndStr , 6, "0", STR_PAD_LEFT);
    
        $query = "SELECT 1 FROM your_table WHERE your_column = {$rndStr} LIMIT 1";
        $db->query($query);
        if (!$db->fetchColumn()) { // value does not exist yet
            // insert new random value
            $query = "INSERT INTO your_table (your_column) VALUES ({$rndStr})";
            $db->query($query);
            $success = true; // will terminate the loop
        } else { // value already exists
            // do nothing - try again in the next loop
        }
    }
    

    您将需要调整代码以适应MySQL通信所使用的代码。

        2
  •  0
  •   Revanth Leonardo    5 年前

    经过调整的版本

    $success = false;
    while (!$success) {
    $rndInt = rand(0, pow(36, 6) - 1);
    $rndStr = base_convert ($rndInt, 10, 36);
    $rndStr = str_pad($rndStr , 6, "0", STR_PAD_LEFT);
    //checking duplicate records
    $checking_duplicate_records = $dbConn->query("SELECT  COUNT(your_column) as 
    duplicate 
    FROM `your_table` 
    WHERE your_column IN ('$rndStr')");
        while($row = $checking_duplicate_records->fetch(PDO::FETCH_ASSOC)) {
        if (!$row['duplicate'] > 0) { // value does not exist yet        
        $success = true; // will terminate the loop
        echo $rndStr; //your unique value
        } else { // value already exists
        // do nothing - try again in the next loop
    }
    }
    }