Automatically add letters in front of an auto-increment fieild

左心房为你撑大大i 提交于 2019-11-28 05:21:59

问题


Is it possible to attach a letter in front of an auto-increment in MySQL. I have several tables in my database, some of which have unique id's created by auto-increment. I want to be able to distinguish between the auto-generated numbers by a letter at the front.

This is not a feature which is absolutely required but it would just help making small tasks easy.


回答1:


Unfortunately you cannot do that. At least not in sql. An autoincrement field is of integer type, so adding a letter there violates the constraint.

You can have a look to the link below for some sort of a solution to this problem.

MySQL auto increment plus alphanumerics in one column

I hope that this can guide you to the right direction.




回答2:


You could create views for the tables that need distinctive letters in front of their ID values, and read the tables through the views:

CREATE VIEW VTableA
AS
SELECT
  CONCAT('A', ID) AS ID,
  other columns
FROM TableA

Same for other tables.




回答3:


The best answer probably depends on what you mean by an alphanumeric ID. Does the alpha part increment in some way, and if so, what are the rules for that? If the alpha part is static, then you don't even need it in the DB: just prepend it to the numeric ID when you output it (perhaps using [s]printf() or similar functions to prepend zeroes so that it's a fixed length?). Without know the full requirement, though, we're all just speculating



来源:https://stackoverflow.com/questions/9648253/automatically-add-letters-in-front-of-an-auto-increment-fieild

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!