0

I have a table code with the following table structure. id is auto incrementing id, the code is a random unique 15 digit code and customer_id is the customer's id. The table has close to 0.13 million rows

 id      code    customer_id 
 1     123...4      1            
 2     124...5      1            
 3     128...3      1            
 4     234...1      2            
 5     678...3      2            
 6     567...8      1            

I have added a column serial_number in table and I want to add a serial_number which will increment for each value of respective customer like below based on the customer_id for existing values. How do I do this in mysql?

 id    code       customer_id  serial_number
 1     123...4      1            1
 2     124...5      1            2
 3     128...3      1            3
 4     234...1      2            1
 5     678...3      2            2
 6     567...8      1            4     

I tried this approach but my mysql connection is getting timed out:

MySQL: Add sequence column based on another field

CREATE temporary table serial_number ( id bigint, serial_number int);
INSERT INTO serial_number ( id, serial_number )
    SELECT id, 
      (SELECT count(*) + 1 FROM code c 
      WHERE c.id < code.id AND c.customer_id = code.customer_id) as    serial_number 
    FROM code;

UPDATE test INNER join serial_number ON code.id = serial_number.id SET   code.serial_number = serial_number.serial_number;

Error Code: 2013. Lost connection to MySQL server during query

4
  • It would be useful if we could see what exact query you used, whether you created a trigger / stored procedure / event or if you're doing this from within your application code. That's why it's always good to post your code, not concepts. Commented Jun 9, 2017 at 8:34
  • i had already put it in my question . here it is again : stackoverflow.com/questions/1600294/… Commented Jun 9, 2017 at 8:37
  • Don't get me wrong, I posted what I did for a reason. It might seem silly to you that I'm asking for that information, but giving the link that you gave without your actual table structure and how you are running the query will yield you almost no help. It's your question and your problem, i tried to help, no one can force you to provide all the info if you don't want to. Good luck with this! Commented Jun 9, 2017 at 8:41
  • @Mjh Thanks. But my table structure is as above. I have added the code I used based on the link above. Commented Jun 9, 2017 at 8:44

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.