【问题标题】:how to add an ID with both string and auto incremented number in sql [duplicate]如何在sql中添加带有字符串和自动递增数字的ID [重复]
【发布时间】:2018-12-01 00:55:34
【问题描述】:

我正在处理一个数据库项目,但我被它的 ID 卡住了。 ID基本上由一个类型和一个数字组成,当我们向表中插入新数据时,它应该自动为数据分配一个新的ID,例如MS-1,MS-2,MS-3,DS-1, DS-2,PC-2,PC-3,我知道如何在 sql 中将字符串与自动递增编号连接起来,但我不确定如何用不同的字符串处理这个问题。提前感谢您提供任何有用的建议!

【问题讨论】:

    标签: mysql sql primary-key auto-increment


    【解决方案1】:

    这正是我的情况,我已经解决了,请在similar 问题中查看我的答案。

    让我也试着系统地回答一下。

    create table my_seq(
    min_value integer,
    Max_value integer,
    last_value integer,
    increment_by tinyint,
    type varchar)ENGINE = InnoDB;
    

    然后创建数据值,例如,

    insert into my_seq(min_value,max_value,last_value,increment_by,type) 
      values(1,99999999,1,1,'foo#','DS'),(1,999999999,1,1,'foo#','MS'),(1,999999999,1,1,'foo#','DOC');
    

    确保您拥有auto-commit=false。 然后,在您的应用程序或数据库代码中这样做,

    //very import to begin the transaction
    begin;
    select CONCAT(type_val,'-',last_value) from my_seq where type_val=? FOR UPDATE;
    
    Read the result in App or database procedure/trigger
    
    update my_seq set last_number=last_number+1 where type_val=?;
    commit;
    

    确保type_val 上有index

    我相信这应该可行。

    【讨论】:

    • 非常感谢您的快速回复,这对您有很大帮助!
    • @binwei 很高兴知道它对您有所帮助。那你介意接受它作为正确答案吗?
    猜你喜欢
    • 2017-08-29
    • 2020-09-04
    • 2017-02-22
    • 2015-12-31
    • 2017-01-10
    • 1970-01-01
    • 2015-11-03
    • 2015-08-28
    • 1970-01-01
    相关资源
    最近更新 更多