Mysql 集成随机唯一id mysql unique number generation

一句代码:

SELECT FLOOR(10000 + RAND() * 89999) AS random_number
FROM table1
WHERE "random_number" NOT IN (SELECT unique_id FROM table2)
LIMIT 1

随机生成5位数字,并且不重复。上面的代码真是给人无限的联想力。

例如:

function get_unique_username($chance=10,$show_sql=FALSE)
{
    global $conn;
    
    // connect db
    if(!$conn) connect();
    
    $output = FALSE;
    $rand   = rand(1,$chance);
    
    $sql = 'SELECT FLOOR('.($rand==5?'10000 + RAND() * 89999':'100000 + RAND() * 899999').') AS random_number FROM gm_users WHERE "random_number" NOT IN (SELECT unique_id FROM gm_ids) LIMIT 1';
    if($show_sql) echo $sql;
    
    $result = mysql_query($sql);
    $row    = mysql_fetch_assoc($result);
    
    if($row['random_number']) 
    {
        $output = $row['random_number'];

        // insert this random_number to table gm_ids
        insert('gm_ids', array('unique_id'=>$output));
    }
    
    return $output;
}

以上实例为,随机生成5或6位数字,并且生成5位数字的记录是 1/10 ($chance)

原创 转载注明 ikeepstudying  >  Mysql 集成随机唯一id mysql unique number generation