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

前端 未结 6 514
我在风中等你
我在风中等你 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: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.

提交回复
热议问题