I have a table with a two component key where the first component is a given id from a related table and the second will be sequential number in order to make the primary key unique. A simple example of the table:
CREATE TABLE a_tbl (
id INT,
seq_num INT,
primary key (id, seq_num)
);
Now, the InnoDB engine in MySQL only allows auto increment on the first element of a multi element primary key. Thus, I thought that I could easily handle the assignment of the second element through a BEFORE INSERT trigger, but it turned out not to work.
I have tried in various ways, but cannot get MySQL to accept the syntax and there is no explanation as to what is wrong with the SQL code. Hopefully, someone can can shed some light on where the problem is and how to get the code to work. Here is the SQL trigger code:
CREATE TRIGGER a_tbl_BEFORE_INSERT
BEFORE INSERT ON a_tbl
FOR EACH ROW BEGIN
SET NEW.seq_num = 1 + (SELECT MAX(COALESCE(seq_num, 0))
FROM a_tbl
WHERE id = NEW.id
);
END