大家都知道,如果将字段设置成 AUTO_INCREMENT 的话,字段就会自增,但是如果删除中间的几条记录后,再插入的时候还是在最大的记录上+1,这样该字段的数据就不连续了,对于删除量很大的表,很容易达到极值现在的需求是写一个函数,通过调用该函数就可以获得该字段未使用的最小值在实现要求的前提下效率最优者给分!

解决方案 »

  1.   

    select id+1 from table1 a where not exists (select 1 from table1 where id=a.id+1) order by id limit 1直接用上述SQL语句就可以简单实现了, 需要在ID上创建主键。
      

  2.   

    int 的最大值是 2147483647 UNSIGNED为 4294967295
    smallInt 的最大值是32767  UNSIGNED为 65535
    bigInt 的最大 9223372036854775807 长度8字节 如果为UNSIGNED,则0到18446744073709551615如果一个表,一天插入8千条,删除5千条,那这个表ID的连续使用量连50%都达不到,而且数字越大执行效率越低!一般这种情况都是用数字字符串来操作,但是现在需求必须使用递归的数字,所以必须考虑这个问题!用SQL语句查询我也想过,但是如果能写一个函数来处理的话,我想效率一定会高一些,起码会减少一次和数据库的对话如果没有得到满意的答案,那就只能使用SQL语句查询或者自己写了~再次感谢 ACMAIN_CHM 的关注
      

  3.   


    +---------------------------------+-------+
    | Variable_name                   | Value |
    +---------------------------------+-------+
    | log_bin_trust_function_creators | OFF   |
    +---------------------------------+-------+
    1 row in set (0.00 sec)mysql> set global log_bin_trust_function_creators=1;
    Query OK, 0 rows affected (0.00 sec)mysql> show variables like 'log_bin_trust_function_creators';
    +---------------------------------+-------+
    | Variable_name                   | Value |
    +---------------------------------+-------+
    | log_bin_trust_function_creators | ON    |
    +---------------------------------+-------+
    1 row in set (0.00 sec)mysql>mysql> use test;
    Database changed
    mysql> select * from  testa ;
    +----+-------+---------+
    | id | user  | message |
    +----+-------+---------+
    |  1 | admin | 12345   |
    |  2 | admin | 45      |
    |  3 | super | 4546    |
    |  4 | super | fsf646  |
    |  6 | super | 4254646 |
    |  7 | admin | 45      |
    +----+-------+---------+
    6 rows in set (0.00 sec)mysql>CREATE FUNCTION GetID() RETURNS int
    begin
        select id+1 into @ID from testa a where not exists (select 1 from testa where id=a.id+1 ) order by id limit 1;
        RETURN @ID;
    end ;
    select @ID;
      

  4.   

    那就直接把
    select id+1 from table1 a where not exists (select 1 from table1 where id=a.id+1) order by id limit 1
    写成函数就行了啊。
    另外,一天insert 8000条,好像离 达到极值 需要太久的时间了。个人建议还是用AUTO_INCREMENT  否则你还需要考虑你自己这个函数的并发访问,锁,效率等问题。
      

  5.   

    sql:
    SELECT min(id)+1 from qt1 a where not exists(select 1 from qt1 where a.id=id-1)
      

  6.   


    如果是日志表的而且这个AUTO_INCREAMENT的字段都与其他表没有关联的话,定期重建这个字段,他会再次从 1开始的。