Add Prefix to auto-increment in mysql db

前端 未结 4 1707
误落风尘
误落风尘 2020-12-03 16:07

I have my database with table test1. It has a primary id \"Id\" which is auto-increment. Now the id is in the format 1,2,3.. . .Is it possible to store the primary Id as PNR

相关标签:
4条回答
  • 2020-12-03 16:40

    Yes you can do it if you have INT prefix. You have id as INT in table

     // START PREFIX
      $query = mysql_query("SELECT id FROM `table_name` ORDER BY id DESC LIMIT 1"); 
      // GET THE LAST ID MAKE SURE IN TABLE YOU 9991
    
      while ($row = mysql_fetch_object($query)) {
        $lastId =  $row->id;
      }
    
      list($prefix,$Id) = explode('999',$lastId );
      $Id = ($Id+1);
      $new_id = '999'.$Id;
      // END PREFIX
    
    
    
    $insertQuery = mysql_query("INSERT INTO `table_name` SET id = '".$new_id."',...");
    
    0 讨论(0)
  • 2020-12-03 16:43

    No. Either add the prefix in the query, or use a view instead.

    0 讨论(0)
  • 2020-12-03 16:53

    Not really, but you can use another column (but a view) this is already covered here: MySQL Auto Increment Custom Values

    0 讨论(0)
  • 2020-12-03 16:56

    Hi, I made it work in this way :

    Products Table (products):

    id_prod(varchar(11), NOT NULL, PK), name(varchar(40))
    

    Products Sequence Table (productidseq):

    id(AI, PK, NOT NULL)
    

    Before Insert Trigger in Products Table:

    CREATE DEFINER=`root`@`localhost` TRIGGER `dbname`.`products_BEFORE_INSERT` BEFORE INSERT ON `products` FOR EACH ROW
    BEGIN
    insert into productidseq (id) values(NULL);
    set new.id_prod = concat('PROD or any prefix here',last_insert_id());
    set @productId = new.id_prod; -- To use outside of trigger this variable is useful.
    END
    

    When you run below query :

    insert into products (name) values('Bat');
    

    data inside tables will we be like this :

    products:

    id | name
    ---|-----
     1 | Bat
    

    productidseq:

    id 
    ---
     1 
    

    If any better way than this or any cons with this, please comment below. Thanks.

    0 讨论(0)
提交回复
热议问题