天天看点

使用uuid替代传统数字序列id

文章出处:http://netkiller.github.io

我一个又一个想法使用uuid 替代 数字数列id

2. 序列id 有范围限制,如果插入失败,id仍然会+1操作,造成浪费,达到最大值后会比较麻烦

3.考虑索引开销,是否会影响性能,我不清楚。我认为对于btree 平衡树增加类a-z还有“-” 使得子树数量增加,索引应该更快。

也听听你的看法?

uuid_test_insert 是负责插入的时候建立uuid())

uuid_test_update 是保护uuid字段不会被修改

使用触发器是因为,我的主键 primary key (`id`) 想用 uuid。  default uuid() 不允许?

create table `test` (

`id` varchar(50) not null default uuid(),

`username` varchar(250) null default null,

`values` varchar(250) null default null ,

primary key (`id`)

)

engine=innodb;

-- --------------------------------------------------------

-- 主机:                           192.168.2.1

-- 服务器版本:                        5.5.25-log - mysql community server (gpl)

-- 服务器操作系统:                      linux

-- heidisql 版本:                  8.0.0.4396

-- 文章出处:http://netkiller.github.io

/*!40101 set @old_character_set_client=@@character_set_client */;

/*!40101 set names utf8 */;

/*!40014 set @old_foreign_key_checks=@@foreign_key_checks, foreign_key_checks=0 */;

/*!40101 set @old_sql_mode=@@sql_mode, sql_mode='no_auto_value_on_zero' */;

-- 导出  表 test.uuid_test 结构

drop table if exists `uuid_test`;

create table if not exists `uuid_test` (

  `uuid` varchar(36) not null,

  `name` varchar(20) not null,

  primary key (`uuid`)

) engine=innodb default charset=utf8 comment='uuid 测试';

-- 数据导出被取消选择。

-- 文章出处:http://netkiller.github.io 

-- 导出  触发器 test.uuid_test_insert 结构

drop trigger if exists `uuid_test_insert`;

set @oldtmp_sql_mode=@@sql_mode, sql_mode='';

delimiter //

create trigger `uuid_test_insert` before insert on `uuid_test` for each row begin

if new.uuid is null or new.uuid = '' or length(new.uuid) != 36 then  

set new.uuid=uuid();  

end if;

end//

delimiter ;

set sql_mode=@oldtmp_sql_mode;

-- 导出  触发器 test.uuid_test_update 结构

drop trigger if exists `uuid_test_update`;

create trigger `uuid_test_update` before update on `uuid_test` for each row begin

set new.uuid = old.uuid;

/*!40101 set sql_mode=ifnull(@old_sql_mode, '') */;

/*!40014 set foreign_key_checks=if(@old_foreign_key_checks is null, 1, @old_foreign_key_checks) */;

/*!40101 set character_set_client=@old_character_set_client */;

下一篇: Gearman 安装