MySQL Auto Increment Custom Values

穿精又带淫゛_ 提交于 2019-12-17 19:59:49

问题


I am trying to make a column in a mysql database that auto increments by one but goes from 0-Z and then rolls.

For example 000, 001, 002, ..., 009, 00A, 00B, ..., 00Z, 010, ..., 0ZZ, ..., 100.

I would like to have the database create the column through an auto incrementing field.

The ideas I have are:

  1. Create a column for each character that goes from 0-36, then auto increment row N (where N is the least significant digit) by 1. Then add a trigger on each column to add 1 to column N-1 when column N reaches 36.
  2. Create a table with 36 rows where each row contains a character 0-Z and pull the appropriate character from the table with similar carry logic from the above
  3. Create a stored procedure to do the appropriate logic from item 1
  4. Have the actual program generate a value and insert it into the table
  5. have a regular auto incrementing value and calculate the next value in the sequence (this is the least optimal as it makes it difficult to parse by a person just looking in the database)

I was hoping that there was something elegant which would allow for this like a built in mechanism to do this that I just do not know. I have no knowledge on stored procedures / triggers so help with it would be greatly appreciated. I think the easiest way would be to have a lookup table for the characters and when row 36 is reached it is reset to 0 and then there is a carry to row N-1.


回答1:


Based on your comments, my recommendation is to do the following:

Use a regular integer auto_increment column as the primary key for the row, and then have a column of type varchar or one of the *text types (depending on your mysql server version and data storage requirements) to store your "identifier" that the customer uses.

The identifier can be auto-generated using a trigger.

If you're going to do lookups based on the identifier (i.e. perhaps the user enters an identifier to "jump to" a record) you will want an index on that column.




回答2:


You can generate custom auto-increment values using stored procedures, as described in:

http://en.latindevelopers.com/ivancp/2012/custom-auto-increment-values/

You will get keys like:

SELECT * FROM custom_autonums;
+----+------------+------------+
| id | seq_1      | seq_2      |
+----+------------+------------+
|  4 | 001-000001 | DBA-000001 |
|  5 | 001-000002 | DBA-000002 |
|  6 | 001-000003 | DBA-000003 |
|  7 | 001-000676 | DBA-000004 |
|  8 | 001-000677 | DBA-000005 |
|  9 | 001-000678 | DBA-000006 |

But you can modify the stored procedures to generate your pattern: 000, 001, 002, ..., 009, 00A, 00B, ..., 00Z, 010, ..., 0ZZ, ..., 100



来源:https://stackoverflow.com/questions/5228408/mysql-auto-increment-custom-values

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