How to get next alpha-numeric ID based on existing value from MySQL

前端 未结 6 508
我在风中等你
我在风中等你 2020-12-19 07:28

First, I apologize if this has been asked before - indeed I\'m sure it has, but I can\'t find it/can\'t work out what to search for to find it.

I need to generate un

相关标签:
6条回答
  • 2020-12-19 07:41
    1. Ensure you have an unique constraint on the Reference column.
    2. Fetch the current max sequential reference the same way you do it in your sample code. You don't actually need to trim the zeroes before you cast to (int), '0001' is a valid integer.
    3. Roll a loop and do your insert inside.
    4. Check affected rows after the insert. You can also check the SQL state for a duplicate key error, but having zero affected rows is a good indication that your insert failed due to inserting an existing Reference value.
    5. If you have zero affected rows, increment the sequential number, and roll the loop again. If you have non-zero affected rows, you're done and have an unique identifier inserted.
    0 讨论(0)
  • 2020-12-19 07:41

    Easiest way to avoid duplicate values for the reference column is to add a unique constraint. So if multiple processes try to set to the same value, MySQL will reject the second attempt and throw an error.

    ALTER TABLE table_name ADD UNIQUE KEY (`company_ref`);
    

    If I were faced with your situation, I would handle the company reference id generation within the application layer, triggers can get messy if not setup correctly.

    0 讨论(0)
  • 2020-12-19 07:46

    A hacky version that works for InnoDB as well.

    Replace the insert to companies with two inserts in a transaction:

        INSERT INTO __keys
          VALUES (LEFT(LOWER('Smiths Joinery'),4), LAST_INSERT_ID(1))
        ON DUPLICATE KEY UPDATE
          num = LAST_INSERT_ID(num+1);
    
        INSERT INTO __companies (comp_name, reference)
        VALUES ('Smiths Joinery',
                CONCAT(LEFT(LOWER(comp_name),4), LPAD(LAST_INSERT_ID(), 4, '0')));
    

    where:

        CREATE TABLE  `__keys` (
          `prefix` char(4) NOT NULL,
          `num` smallint(5) unsigned NOT NULL,
          PRIMARY KEY (`prefix`)
        ) ENGINE=InnoDB COLLATE latin1_general_ci;
    
        CREATE TABLE  `__companies` (
          `comp_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
          `comp_name` varchar(45) NOT NULL,
          `reference` char(8) NOT NULL,
          PRIMARY KEY (`comp_id`)
        ) ENGINE=InnoDB COLLATE latin1_general_ci;
    

    Notice:

    • latin1_general_ci can be replaced with utf8_general_ci,
    • LEFT(LOWER('Smiths Joinery'),4) would better become a function in PHP
    0 讨论(0)
  • 2020-12-19 07:47

    Given you're using InnoDB, why not use an explicit transaction to grab an exclusive row lock and prevent another connection from reading the same row before you're done setting a new ID based on it?

    (Naturally, doing the calculation in a trigger would hold the lock for less time.)

    mysqli_query($link, "BEGIN TRANSACTION");
    $query = "SELECT `company_ref`
                FROM `companies`
              WHERE
                `company_ref` LIKE '$fourLetters%'
              ORDER BY `company_ref` DESC
              LIMIT 1
              FOR UPDATE";
    $last = mysqli_fetch_assoc(mysqli_query($link, $query));
    $newNum = ((int) ltrim(substr($last['company_ref'],4),'0')) + 1;
    $newRef = $fourLetters.str_pad($newNum, 4, '0', STR_PAD_LEFT);
    mysqli_query($link, "INSERT INTO companies . . . (new row using $newref)");
    mysqli_commit($link);
    

    Edit: Just to be 100% sure I ran a test by hand to confirm that the second transaction will return the newly inserted row after waiting rather than the original locked row.

    Edit2: Also tested the case where there is no initial row returned (Where you would think there is no initial row to put a lock on) and that works as well.

    0 讨论(0)
  • 2020-12-19 08:03

    If you are using MyISAM, then you can create a compound primary key on a text field + auto increment field. MySQL will handle incrementing the number automatically. They are separate fields, but you can get the same effect.

    CREATE TABLE example (
    company_name varchar(100),
    key_prefix char(4) not null,
    key_increment int unsigned auto_increment,
    primary key co_key (key_prefix,key_increment)
    ) ENGINE=MYISAM;
    

    When you do an insert into the table, the key_increment field will increment based on the highest value based on key_prefix. So insert with key_prefix "smit" will start with 1 in key_inrement, key_prefix "jone" will start with 1 in key_inrement, etc.

    Pros:

    • You don't have to do anything with calculating numbers.

    Cons:

    • You do have a key split across 2 columns.
    • It doesn't work with InnoDB.
    0 讨论(0)
  • 2020-12-19 08:07

    How about this solution with a trigger and a table to hold the company_ref's uniquely. Made a correction - the reference table has to be MyISAM if you want the numbering to begin at 1 for each unique 4char sequence.

    DROP TABLE IF EXISTS company;
    CREATE TABLE company (
      company_name varchar(100) DEFAULT NULL,
      company_ref char(8) DEFAULT NULL
    ) ENGINE=InnoDB
    
    DELIMITER ;;
    CREATE TRIGGER company_reference BEFORE INSERT ON company
    FOR EACH ROW BEGIN
       INSERT INTO reference SET company_ref=SUBSTRING(LOWER(NEW.company_name), 1, 4), numeric_ref=NULL;
       SET NEW.company_ref=CONCAT(SUBSTRING(LOWER(NEW.company_name), 1, 4), LPAD(CAST(LAST_INSERT_ID() AS CHAR(10)), 4, '0'));
    END ;;
    DELIMITER ;
    
    DROP TABLE IF EXISTS reference;
    CREATE TABLE reference (
    company_ref char(4) NOT NULL DEFAULT '',
    numeric_ref int(11) NOT NULL AUTO_INCREMENT,
    PRIMARY KEY (company_ref, numeric_ref)
    ) ENGINE=MyISAM;
    

    And for completeness here is a trigger that will create a new reference if the company name is altered.

    DROP TRIGGER IF EXISTS company_reference_up;
    DELIMITER ;;
    CREATE TRIGGER company_reference_up BEFORE UPDATE ON company
    FOR EACH ROW BEGIN
       IF NEW.company_name <> OLD.company_name THEN
          DELETE FROM reference WHERE company_ref=SUBSTRING(LOWER(OLD.company_ref), 1, 4) AND numeric_ref=SUBSTRING(OLD.company_ref, 5, 4);
          INSERT INTO reference SET company_ref=SUBSTRING(LOWER(NEW.company_name), 1, 4), numeric_ref=NULL;
          SET NEW.company_ref=CONCAT(SUBSTRING(LOWER(NEW.company_name), 1, 4), LPAD(CAST(LAST_INSERT_ID() AS CHAR(10)), 4, '0'));
       END IF;
    END;
    ;;
    DELIMITER ;
    
    0 讨论(0)
提交回复
热议问题