我在网上看到很多PHP+Mysql的论坛设计文档采用 字母+数字 作为标识。
例:
table
id name
n1000001 one
n1000002 two
n1000003 three
这个是怎么实现的呢?
为什么一定要字母+数字?
直接用数字不可以吗?
如果前面都是N这样,你还不如取数据的时候直接在前面加个N
取之前把表锁住 再增加,在放回去
1.假设你可以用auto_increment属性
建立一个专用计数表:
create table id_table (id int unsigned auto_increment primary key not null);
在程序中,插入记录并且取出就是:
insert into id_table values (null);
select last_insert_id();
两句SQL查询语句连用,然后根据取出的值再去加上你要前缀并写入相应的数据表。
因为last_insert_id()是和具体客户程序相关联的,即使在发出insert和select语句的时间间隔中又有其它进程发出了insert语句来生成了新的编号,last_insert_id()检索出的仍然是它所在进程生成的序号,所以也就不需要锁定表了。你可以自己开两个mysql客户端链接来测试,分别先用insert语句插入记录,再分别用last_insert_id来看。
2.假设你不用auto_increment属性
建立一个专用计数表:
create table id_table (id int unsigned primary key not null);
并初始化:
insert into id_table values (0);
在程序中,插入记录并且取出就是:
update id_table set id = last_insert_id(id + 1);
select last_insert_id();
两句SQL查询语句连用,然后根据取出的值再去加上你要前缀并写入相应的数据表。
自己测试吧。并看MySQL手册关于last_insert_id([expr])的介绍。