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

前端 未结 6 524
我在风中等你
我在风中等你 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 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 ;
    

提交回复
热议问题