Search code examples
mysqlauto-increment

Mysql Auto Increment For Group Entries


I need to setup a table that will have two auto increment fields. 1 field will be a standard primary key for each record added. The other field will be used to link multiple records together.

Here is an example.

field 1  |  field 2
  1           1
  2           1
  3           1
  4           2
  5           2
  6           3

Notice that each value in field 1 has the auto increment. Field 2 has an auto increment that increases slightly differently. records 1,2 and 3 were made at the same time. records 4 and 5 were made at the same time. record 6 was made individually.

Would it be best to read the last entry for field 2 and then increment it by one in my php program? Just looking for the best solution.


Solution

  • You should have two separate tables.

    ItemsToBeInserted
    id, batch_id, field, field, field
    
    BatchesOfInserts
    id, created_time, field, field field
    

    You would then create a batch record, and add the insert id for that batch to all of the items that are going to be part of the batch.

    You get bonus points if you add a batch_hash field to the batches table and then check that each batch is unique so that you don't accidentally submit the same batch twice.

    If you are looking for a more awful way to do it that only uses one table, you could do something like:

    $batch = //Code to run and get 'SELECT MAX(BATCH_ID) + 1 AS NEW_BATCH_ID FROM myTable' 
    

    and add that id to all of the inserted records. I wouldn't recommend that though. You will run into trouble down the line.