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

Generate a random value that doesn't exist in the same column

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

我尝试了这个我在某处找到的 FLOOR(RAND() * 401) + 100,但它只生成数字而且...仅此而已。

我迷路了。

请各位数据库高手,用你们的随机数照亮我的路;-;

SELECT LPAD(CONV(RAND() * POW(36, 6), 10, 36), 6, 0)

这将创建一个包含 6 个字符的 "random" 字母数字值。

但是:

  • 您需要检查您的 table 中是否已存在该值。
  • 分布不均,因为 rand() 返回一个只有 23 位精度的 FLOAT,而 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 通信的代码。

调整后的版本

$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
}
}
}