美文网首页
MySQL生成随机字符串的三种方法

MySQL生成随机字符串的三种方法

作者: 牧码人zhouz | 来源:发表于2021-03-17 15:04 被阅读0次

    一、使用rand函数

    select substring(md5(rand()), 1, length);
    

    说明

    • rand():随机函数,会生成0~1之间的随机数
    • md5(input):散列函数,根据输入值的不同,生成不同的32位字符串(但只有0~9,a~f共16种字符)
    • substring(string, position, length):字符串截取函数,会截取字符串stringposition位置开始共length个字符的子串。

    比如说,要生成一个10位的随机字符串,可以使用如下语句:

    select substring(md5(rand()), 1, 10);
    

    运行结果:

    mysql> select substring(md5(rand()), 1, 10);
    +-------------------------------+
    | substring(md5(rand()), 1, 10) |
    +-------------------------------+
    | f4c11e1f20                    |
    +-------------------------------+
    1 row in set (0.00 sec)
    

    该语句只能生成最长32位(但只有0~9,a~f共16种字符)的字符串,如果需要更长的字符,可以使用concat函数连接多个字符串,如下所示:

    select concat(substring(md5(rand()), 1, 10),  md5(rand()));
    

    这个语句可以生成长度为42个字符的字符串。
    运行结果:

    mysql> select concat(substring(md5(rand()), 1, 10),  md5(rand()));
    +-----------------------------------------------------+
    | concat(substring(md5(rand()), 1, 10),  md5(rand())) |
    +-----------------------------------------------------+
    | ba277110796b954eba43df14276eb80eef915685d9          |
    +-----------------------------------------------------+
    1 row in set (0.00 sec)
    

    二、使用uuid函数

    select replace(uuid(),  '-',  '');
    

    说明

    因为 uuid() 函数返回的字符串中会包含特殊字符 "-" , 所以我们需要通过 replace 函数将这个特殊字符全部替换掉。这种方式会得到一个32位的字符串,如果有长度要求,可以用substring或concat函数裁剪或拼接。

    运行结果:

    mysql> select replace(uuid(),  '-',  '');
    +----------------------------------+
    | replace(uuid(),  '-',  '')       |
    +----------------------------------+
    | 6fe064bc86ee11ebbebe0242ac110002 |
    +----------------------------------+
    1 row in set (0.00 sec)
    
    mysql> select substring(replace(uuid(),  '-',  ''), 1, 30);
    +----------------------------------------------+
    | substring(replace(uuid(),  '-',  ''), 1, 30) |
    +----------------------------------------------+
    | 8b3c7f1386ee11ebbebe0242ac1100               |
    +----------------------------------------------+
    1 row in set (0.00 sec)
    
    mysql> select concat(substring(replace(uuid(),  '-',  ''), 1, 30), replace(uuid(),  '-',  ''));
    +----------------------------------------------------------------------------------+
    | concat(substring(replace(uuid(),  '-',  ''), 1, 30), replace(uuid(),  '-',  '')) |
    +----------------------------------------------------------------------------------+
    | cca1f72a86ee11ebbebe0242ac1100cca1f75b86ee11ebbebe0242ac110002                   |
    +----------------------------------------------------------------------------------+
    1 row in set (0.01 sec)
    

    三、使用自定义函数

    DELIMITER $$
    DROP FUNCTION IF EXISTS rand_string$$
    CREATE  FUNCTION `rand_string`(num INT) RETURNS varchar(255) CHARSET UTF8
    BEGIN
        DECLARE origin_str char(52) DEFAULT 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        DECLARE return_str varchar(255) DEFAULT '';
        DECLARE i INT DEFAULT 0;
        WHILE i < num DO
            SET return_str = CONCAT(return_str, SUBSTRING(origin_str , FLOOR(1 + RAND()*52 ),1));
            SET i = i +1;
        END WHILE;
        RETURN return_str;
    END $$
    DELIMITER ;
    

    说明

    • DELIMITER $$ 定义结束符。MySQL默认的结束符是分号,但是函数体中可能用到分号。为了避免冲突,需要另外定义结束符;
    • DROP FUNCTION IF EXISTS rand_string$$ 如果函数rand_string已经存在了,就删除掉;
    • CREATE FUNCTION 创建函数rand_string,函数的参数是num,返回值是varchar(255);
    • 函数体放在BEGIN 与 END之间;
    • DECLARE 声明变量,return_str类型是varchar(255),默认值是空;
    • FLOOR(1 + RAND()*52 )获取到1到52之间的随机数
    • CONCAT连接多个字符串;
    • RETURN 返回拼接后的字符串return_str。

    运行效果

    mysql> DELIMITER $$
    mysql> DROP FUNCTION IF EXISTS rand_string$$
    Query OK, 0 rows affected (0.07 sec)
    
    mysql> CREATE  FUNCTION `rand_string`(num INT) RETURNS varchar(255) CHARSET UTF8
        -> BEGIN
        ->     DECLARE origin_str char(52) DEFAULT 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        ->     DECLARE return_str varchar(255) DEFAULT '';
        ->     DECLARE i INT DEFAULT 0;
        ->     WHILE i < num DO
        ->         SET return_str = CONCAT(return_str, SUBSTRING(origin_str , FLOOR(1 + RAND()*52 ),1));
        ->         SET i = i +1;
        ->     END WHILE;
        ->     RETURN return_str;
        -> END $$
    Query OK, 0 rows affected (0.01 sec)
    
    mysql> DELIMITER ;
    mysql> select rand_string(10);
    +-----------------+
    | rand_string(10) |
    +-----------------+
    | OybKzoWRrm      |
    +-----------------+
    1 row in set (0.00 sec)
    

    相关文章

      网友评论

          本文标题:MySQL生成随机字符串的三种方法

          本文链接:https://www.haomeiwen.com/subject/zeqecltx.html