MySQL MySQL中的自动增量varchar

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14038586/
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-31 15:55:22  来源:igfitidea点击:

Auto Increment varchar in MySQL

mysqlsqlselect

提问by Ye Wint

Is there a way to set primary key auto increment, type of varchar in mySql?

有没有办法在mySql中设置主键自动增量,varchar类型?

回答by John Woo

NONE. So far, AUTO_INCREMENTcan be set for INTonly. It needs to have your own logic to do that. eg,

。到目前为止,AUTO_INCREMENT只能设置为INT。它需要有你自己的逻辑来做到这一点。例如,

  • Get Last ID
  • Get the INT part within the string
  • Increment the value
  • Concatenate
  • Save to DB
  • 获取最后一个 ID
  • 获取字符串中的 INT 部分
  • 增加值
  • 连接
  • 保存到数据库

回答by Nidhish Krishnan

Duplication of MySQL - how to use VARCHAR as AUTO INCREMENT Primary Key

复制MySQL - 如何使用 VARCHAR 作为 AUTO INCREMENT 主键

According to my point of view you have to change it as integer type. Since AUTO_INCREMENTis for INTtype only, moreover setting the field as PRIMARY KEYwhich prevents duplication of values.

根据我的观点,您必须将其更改为整数类型。由于AUTO_INCREMENT仅用于INT类型,此外将字段设置为PRIMARY KEY可防止值重复。

回答by Rahul

AutoIncrement fields are integer in mysql.

AutoIncrement 字段在 mysql 中是整数。

You can mirror the auto-increment field in a varchar field and create a trigger which updates the varchar field on insert/update.

您可以镜像 varchar 字段中的自动增量字段,并创建一个触发器,在插入/更新时更新 varchar 字段。

Create Trigger

创建触发器

回答by kolapopo

for my experience, you can make Varcar ID as auto increment but you must have logic..let say

根据我的经验,您可以将 Varcar ID 设置为自动增量,但您必须有逻辑..让说

 Dim crnum As String = "CR00001"
    Dim iTemp As Integer = 0

                iTemp = CInt(crnum.Substring(4, crnum.Length - 4)) '// get only the #'s from String and Convert them to Integer.
                iTemp += 1 '// increase the ID # + 1.
                crnum = crnum.Substring(0, 4) & iTemp.ToString("00000") '// set the ID back with String and #'s formatted to 5 digit #.

but you must do your own logic ,because after u run it for second time it will become duplicate primary key so, you must think your logic to apply your code. Anything is possible. ;)

但是你必须做你自己的逻辑,因为在你第二次运行它之后它会变成重复的主键,所以你必须考虑你的逻辑来应用你的代码。一切皆有可能。;)