I'm creating a simple set of tables to store a number of lists. The first table, describes the lists that I have and second describes items on those lists - the tables are defined like so:
CREATE TABLE `listman_list` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`title` varchar(100) NOT NULL,
`description` varchar(1000) NOT NULL,
`id_counter` integer UNSIGNED NOT NULL
)
CREATE TABLE `listman_listitem` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`number` integer UNSIGNED NOT NULL,
`title` varchar(100) NOT NULL,
`description` varchar(10000) NOT NULL,
`list_id` integer NOT NULL,
)
Each listitem
has the number field which describes its unique number relative to the list. This is to enable listitems to be uniquely numbered for the list (but not globally, this numbering is distinct from its primary key). E.g. so I can have list one with items 1,2,3 annd list two with items 1,2,3 etc.
Now, what is the best way to number the items in the second table? At the moment I have a pair of triggers:
CREATE TRIGGER set_listitem_number
BEFORE INSERT ON listman_listitem
FOR EACH ROW
SET NEW.number = (SELECT DISTINCT id_counter FROM listman_list id=NEW.list_id);
CREATE TRIGGER inc_listcounter
AFTER INSERT ON listman_listitem
FOR EACH ROW
UPDATE listman_list SET id_counter = id_counter+1 WHERE id=NEW.list_id;
The first sets the list item number from the list table, prior to insertion whilst the second increments the counter in the list table after it has been successfully inserted (I heard that modifying other tables before insertion had some undesirable consequences with MySQL if the transaction failed - as the before triggers would not be undone).
Is this a good way to do it - or should I do it under a transaction in the application code manually, or should I do it some other way entirely?
Thanks for your help - I may be fussing about trivia here, but I don't have a lot of experience with databases.