我花了很多时间寻找解决方案,并提出了以下mysql函数,该函数使用标准MySQL函数生成一个随机UUID(即UUIDv4)。我正在回答我自己的问题,以期分享它,希望对大家有用。
-- Change delimiter so that the function body doesn't end the function declarationDELIMITER //CREATE FUNCTION uuid_v4() RETURNS CHAr(36)BEGIN -- Generate 8 2-byte strings that we will combine into a UUIDv4 SET @h1 = LPAd(HEx(FLOOR(RAND() * 0xffff)), 4, '0'); SET @h2 = LPAd(HEx(FLOOR(RAND() * 0xffff)), 4, '0'); SET @h3 = LPAd(HEx(FLOOR(RAND() * 0xffff)), 4, '0'); SET @h6 = LPAd(HEx(FLOOR(RAND() * 0xffff)), 4, '0'); SET @h7 = LPAd(HEx(FLOOR(RAND() * 0xffff)), 4, '0'); SET @h8 = LPAd(HEx(FLOOR(RAND() * 0xffff)), 4, '0'); -- 4th section will start with a 4 indicating the version SET @h4 = CONCAt('4', LPAd(HEx(FLOOR(RAND() * 0x0fff)), 3, '0')); -- 5th section first half-byte can only be 8, 9 A or B SET @h5 = CONCAt(HEx(FLOOR(RAND() * 4 + 8)), LPAd(HEx(FLOOR(RAND() * 0x0fff)), 3, '0')); -- Build the complete UUID RETURN LOWER(CONCAt( @h1, @h2, '-', @h3, '-', @h4, '-', @h5, '-', @h6, @h7, @h8 ));END//-- Switch back the delimiterDELIMITER ;
注意:所使用的伪随机数生成(MySQL’s
RAND)在密码上不是安全的,因此存在一些偏差,可能会增加冲突风险。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)