How to add a series of string in incrementing id in any table?

前端 未结 4 688
野趣味
野趣味 2021-01-21 14:46

I have MySQL Table with an Order table in a DB this table has an auto-incremental id. Up-till now we have general numeric Order-ID likewise 1,2,3,4,5... From now onwards I have

相关标签:
4条回答
  • 2021-01-21 15:01

    Altering an existing auto_increment column does not sound like a good idea - do you really have to do this? Instead, why not just modify your select query to return a suitably formatted id? By doing so, you maintain referential integrity, and you are also free to change the order id format at any time in the future, without having to update your database.

    SELECT id, CONCAT('A2', LPAD(id, 4, '0')) AS order_id FROM <table>;
    

    Example output:

    +------+----------+
    | id   | order_id |
    +------+----------+
    |    1 | A20001   |
    |    2 | A20002   
    ...
    |  999 | A20999   |
    | 1000 | A21000   |
    | 1001 | A21001   |
    +------+----------+
    
    0 讨论(0)
  • 2021-01-21 15:02

    something along the lines of:

    "AR2" . str_pad((int) $ordernumber, 4, "0", STR_PAD_LEFT);
    

    jim

    [edit] - i'm assuming this is for display purposes as stated elsewhere, the ID field on the DB is integer!!

    0 讨论(0)
  • 2021-01-21 15:16

    You can't have an auto-increment which is not a numeric field. You will better keep the current auto-incrementing column, and add a new one which you will compute manually according to your rules.

    You'll probably want to use the MAX() function to get the latest order and generate the next value: remember to do it within a transaction.

    You could create a function or a trigger, to do the insert cleanly for you.

    0 讨论(0)
  • 2021-01-21 15:25

    You can't add prefixes directly to the database. However, when selecting it you can prepend it.

    SELECT concat('A', id) as id FROM table
    

    To get the effect of starting from 20000 you can set the auto increment starting value.

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