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

时间:2016-03-27 11:39:18

标签: mysql random varchar

我已经用Google搜索了,但我刚刚找到了类似的答案 我不是后端开发人员,因此我不了解很多SQL。我需要生成并插入一个6位数的随机值,该值涉及在同一列中不存在的数字和字符(varchar,我认为)。

我试过这个FLOOR(RAND() * 401) + 100,我发现它在哪里,但它只是生成数字而且......仅此而已。

我输了。

请数据库的主人用你的随机数点亮我的方式; - ;

2 个答案:

答案 0 :(得分:1)

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通信的代码。

答案 1 :(得分:0)

经过调整的版本

$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
}
}
}
相关问题