2

我需要能够安全地插入具有第一个可用 ID 的行。我阅读了很多关于 PRIMARY_KEY 和 AUTO_INCREMENT 以及所有这些东西的答案,但这是另一回事。我需要保留并能够使用固定 ID 范围从 1 到 60000 的数据库。有没有办法用 MySQL 做到这一点?编写自己的函数来检查最近的“免费”ID,这不是一种选择,因为多用户使用可能会发生冲突。

在最好的情况下,MySQL 会以某种方式与 PRIMARY_KEY 一起工作,但会重用密钥。

4

4 回答 4

1

你在写,你需要考虑并发问题,因此你需要实现一个表锁机制

1)锁定mysql表

2)插入记录,您可以只使用 auto_increment 属性,因为不会同时添加两个值(如果无论如何使用,我认为您不必锁定表)

3) 如果您不想使用 auto_increment,上述任何建议的代码都可以使用

于 2013-11-08T17:48:05.143 回答
1

按着这些次序:

1)创建一个带有列的序列表id, rowstate

2) 将 ids 插入1-60000到 rowstate 1

3) 每当您想在主表中插入时,从具有 rowstate=1 的序列表中搜索最低 id 并将序列更新为 -1。当你想从主表中删除一条记录时,将 id 的 rowstate 设置为 1。

于 2013-11-08T17:31:43.247 回答
0

You can try like this:

INSERT INTO tableName (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE id=(Select max(id)+1 from tableName);

For more info: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

OR

Getting highest id from table and increament it and insert your row.

Select max(id) from tableName;

You will get the id. Than add 1 it and insert into table. Additionally you can check it should be less than 60000.

I know this is not the best answer, but can be consider as second alternative.

于 2013-11-08T17:30:23.673 回答
0

要获得第一个id免费的,你可以做

select id - (id-ra) as lowest
from
(
  select id, @r := @r + 1 as ra
  from t, (select @r := 0) rank
  order by id
)
x 
where ra <> id
limit 1

SQLFiddle 演示

您可以将其放入在操作期间锁定表的过程中

delimiter |
CREATE PROCEDURE create_save ()
BEGIN     

    LOCK TABLES your_table WRITE;

    set @lowid := 0;
    select @lowid := id - (id-ra)
    from
    (
      select id, @r := @r + 1 as ra
      from your_table, (select @r := 0) rank
      order by id
    )
    x 
    where ra <> id
    limit 1;

    if @lowid between 1 and 59999
    then
        insert into your_table (id, othercolumn)
        select @lowid, 12345;
    end if;

    UNLOCK TABLES;

end
|
delimiter ;
于 2013-11-08T17:33:40.767 回答