【问题标题】:SQL userID auto incrementSQL 用户 ID 自动递增
【发布时间】:2013-06-25 12:23:36
【问题描述】:

Mysql数据库就是这样的;

userID -> primaryKey, required, unsigned integer, auto increment, unique
usermail -> unique,varchar,required

我正在创建新用户。 userId 是自动递增的。如果之前插入了usermail,则会发生错误。我的问题是这个

Let's think that userID is between 1-9.(there are 9 users now). 
Somebody has inserted same usermail before and took error. 
After that,new user inserted another usermail but userID became 11 instead 10. 
Why? What should i do to make it 10?

【问题讨论】:

    标签: mysql sql database unique userid


    【解决方案1】:

    您是否有必要从数据库属性本身增加用户 ID。因为我的意思是,在插入任何记录之前,只需从数据库中检索最后一个用户 ID,将其存储在一个整数变量中,然后将其递增并与新记录一起插入回数据库。

    假设您的最后一个用户 ID 是 9。 使用这个查询 - Select max(userID) from "your table";

    int x=0;
    SqlDataReader dr=com.ExecuteReader();
    if(dr.HasRows)
    {
        While(dr.Read())
        {
           x=Convert.ToInt32(dr.GetString(0).ToString);
        }
    }
    x=x+1;
    

    现在,既然您有了新的x 值,就可以轻松地将其插入到带有新记录的数据库中。 这样将遵循自动递增,即使发生故障插入也不会完成,UserID 不会增加。

    【讨论】:

    • 是的,这个解决方案正是我想要的。谢谢
    【解决方案2】:

    当出现错误时,它似乎是在插入一个新行并增加唯一 ID。出错时,您需要查询表以获取最新 ID 并重置自动增量值

    ALTER TABLE `table_name` AUTO_INCREMENT =new_number_here
    

    在这里找到:http://forums.mysql.com/read.php?20,16088,17748#msg-17748

    【讨论】:

    • 是否可以在 my.ini 文件中添加参数?这是一个解决方案吗?
    【解决方案3】:

    您必须将插入子句与下面的选择检查合并。

    这是 mysql 的一种行为,它也会为错误和成功插入增加计数器

    INSERT INTO [table name] SELECT '[value1]', '[value2]' FROM DUAL
    WHERE NOT EXISTS(
    SELECT [column1] FROM [same table name]
    WHERE [column1]='[value1]'
    AND [column2]='[value2]' LIMIT 1    )
    

    在这里您可以看到如何使用此技术防止 insert 子句 insert-where-not-exists 插入数据时计数器会增加,并且重复数据将被忽略

    【讨论】:

    • 有没有办法像在my.ini文件中添加一个参数来解决这个问题?
    • 不,没有办法通过查询或my.ini来阻止auto_incrementcounter,这里是mysql开发人员dev.mysql.com/doc/refman/5.5/en/…关于AUTO_INCREMENT Handling in InnoDB的详细信息
    猜你喜欢
    • 2015-07-05
    • 1970-01-01
    • 2018-08-06
    • 2014-12-05
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 2011-01-31
    • 2010-10-04
    相关资源
    最近更新 更多