MySQL: Add sequence column based on another field

前端 未结 3 897

I\'m working on some legacy code/database, and need to add a field to the database which will record a sequence number related to that (foreign) id.

Example table da

3条回答
  •  醉酒成梦
    2020-11-27 18:18

    This should work but is probably slow:

    CREATE temporary table seq ( id int, seq int);
    INSERT INTO seq ( id, seq )
        SELECT id, 
          (SELECT count(*) + 1 FROM test c 
          WHERE c.id < test.id AND c.account = test.account) as seq 
        FROM test;
    
    UPDATE test INNER join seq ON test.id = seq.id SET test.seq = seq.seq;
    

    I have called the table 'test'; obviously that needs to be set correctly. You have to use a temporary table because MySQL will not let you use a subselect from the same table you are updating.

提交回复
热议问题