Wednesday, April 30, 2008

Multi-Column AutoIncrement "fix" with InnoDB (or any storage engine) with MySQL

I was tooling around with triggers today, as a friend was telling me that only 2 engines support multi-column Auto-Increment.

As it turns out, in MySQL 5.0 (and MySQL 5.1) this can be done easily enough through a trigger, like what is happening below:


DROP TRIGGER IF EXISTS `insert_users_id`//
CREATE TRIGGER `insert_users_id` BEFORE INSERT ON `users`
FOR EACH ROW BEGIN
SET NEW.id = (SELECT IFNULL(MAX(id),0) FROM users u WHERE u.site_id=NEW.site_id )+1;
END
//


This should allow a little more flexibility with Auto-Numbering as well. If you wanted to find the first available number instead of the Max...that should probably be possible...though certainly more resource intensive.