php 在mysql db中添加前缀以自动递增

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5991148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:07:51  来源:igfitidea点击:

Add Prefix to auto-increment in mysql db

phpmysql

提问by hjaffer2001

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 PNR1,PNR2,PNR3 .. . . and so on(with auto-increment).

我有我的数据库表 test1。它有一个自动递增的主 ID“Id”。现在 id 的格式为 1,2,3.. 。. 是否可以将主 ID 存储为 PNR1,PNR2,PNR3 .. . . 依此类推(自动递​​增)。

回答by Ignacio Vazquez-Abrams

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

否。要么在查询中添加前缀,要么改用视图。

回答by radosch

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

不是真的,但你可以使用另一列(但一个视图),这已经在这里介绍: MySQL Auto Increment Custom Values

回答by test

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

是的,如果您有 INT 前缀,您可以这样做。您在表中的 id 为 INT

 // 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."',...");

回答by Himakar

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):

产品序列表(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.

如果有比这更好的方法或任何缺点,请在下面评论。谢谢。