MySQL: Establishing a Sequence Column Dependent on a Foreign Field
In the realm of database management, it becomes imperative at times to modify existing structures to accommodate new data requirements. Such is the case when a sequence number needs to be assigned to records based on a specific foreign key.
Consider a table with columns ID, ACCOUNT, and some_other_stuff. The goal is to introduce a new column, SEQ, which increments uniquely for each distinct ACCOUNT value, like so:
ID ACCOUNT SEQ some_other_stuff 1 1 1 ... 2 1 2 ... 3 1 3 ... 4 2 1 ... 5 2 2 ... 6 1 4 ...
SQL-Based Solution:
MySQL empowers us with triggers, a powerful mechanism to automatically execute predefined actions upon data manipulation events. In this instance, a trigger can be employed to populate the SEQ column with appropriate values during record insertion. The trigger code:
CREATE TRIGGER trg_mytable_bi BEFORE INSERT ON mytable FOR EACH ROW BEGIN DECLARE nseq INT; SELECT COALESCE(MAX(seq), 0) + 1 INTO nseq FROM mytable WHERE account = NEW.account; SET NEW.seq = nseq; END;
Breakdown:
The above is the detailed content of How to Implement a Sequence Column Dependent on a Foreign Key in MySQL?. For more information, please follow other related articles on the PHP Chinese website!