uuid的格式
代码如下:
string string = uuid.randomuuid().tostring(); system.out.println(“uuid:” + string); uuid:05ba463f-1dab-471f-81c7-58e0b06f35f0
数据库中直接存储uuid的坏处:
完全‘随机'的字符串,例如由md5()、sha1()、uuid()产生的。它们产生的每一个新值都会被任意地保存在很大的空间范围内,这会减慢insert及一些select查询。1)它们会减慢insert查询,因为插入的值会被随机地放入索引中。这会导致分页、随机磁盘访问及聚集存储引擎上的聚集索引碎片。2)它们会减慢select查询,因为逻辑上相邻的行会分布在磁盘和内存中的各个地方。3)随机值导致缓存对所有类型的查询性能都很差,因为它们会使缓存赖以工作的访问局部性失效。如果整个数据集都变得同样“热”的时候,那么把特定部分的数据缓存到内存中就没有任何的优势了。并且如果工作集不能被装入内存中,缓存就会进行很多刷写的工作,并且会导致很多缓存未命中。
如果保存uuid值,就应该移除其中的短横线,更好的办法是使用uhex()把uuid值转化为16字节的数字,并把它保存在binary(16)列中。
代码如下:
delimiter $$ create function `guidtobinary`( $data varchar(36) ) returns binary(16) begin declare $result binary(16) default null; if $data is not null then set $data = replace($data,'-',”); set $result = concat(unhex(substring($data,7,2)),unhex(substring($data,5,2)),unhex(substring($data,3,2)), unhex(substring($data,1,2)), unhex(substring($data,11,2)),unhex(substring($data,9,2)),unhex(substring($data,15,2)) , unhex(substring($data,13,2)), unhex(substring($data,17,16))); end if; return $result; end $$ create function `toguid`( $data binary(16) ) returns char(36) charset utf8 begin declare $result char(36) default null; if $data is not null then set $result = concat(hex(substring($data,4,1)),hex(substring($data,3,1)),hex(substring($data,2,1)), hex(substring($data,1,1)) , ‘-', hex(substring($data,6,1)),hex(substring($data,5,1)),'-', hex(substring($data,8,1)) , hex(substring($data,7,1)),'-', hex(substring($data,9,2)),'-',hex(substring($data,11,6))); end if; return $result; end
代码如下:
create function `uuidtobin`() returns binary(16) begin declare my_uuid char(36); set my_uuid = uuid(); return concat(unhex(left(my_uuid,8)),unhex(mid(my_uuid,10,4)),unhex(mid(my_uuid,15,4)),unhex(mid(my_uuid,20,4)),unhex(right(my_uuid,12))); end create function `bintouuid`(uuid binary(16)) returns char(36) begin return concat(hex(left(uuid,4)),'-', hex(mid(uuid,5,2)),'-', hex(mid(uuid,7,2)),'-',hex(mid(uuid,9,2)),'-',hex(right(uuid,6))); end
