MySQL: Grouped primary key with InnoDB

后端 未结 2 450
长情又很酷
长情又很酷 2021-01-24 02:14

Is there an equivalent to a grouped primary key using an InnoDB MySQL database and allowing auto-increment on the second key?

What I am trying to implement is a table to

2条回答
  •  离开以前
    2021-01-24 02:53

    In case this can help anyone else this was my solution.

    I could not simply use a trigger as MySQL does not yet (or at least my version 5.1.53) support the ability to use a trigger to update the table the trigger is called on. So I created a sequence table:

    CREATE TABLE image_seq (
        parent_id INT(11) NOT NULL,
        catagory INT(11) NOT NULL,
        next_seq_id INT(11) NOT NULL,
        KEY(catagory),
        PRIMARY KEY(parent_id, catagory);
    );
    

    And then created a trigger on the images table:

    CREATE TRIGGER bi_image_trig
    BEFORE INSERT ON images
    FOR EACH ROW
    BEGIN
    
    DECLARE id INT UNSIGNED DEFAULT 1;
     SELECT next_seq_id + 1 INTO id FROM image_seq WHERE parent_id=NEW.parent_id AND       catagory=NEW.catagory;
    SET NEW.image_id = id;
    UPDATE image_seq SET next_seq_id=id WHERE parent_id=NEW.parent_id AND catagory=NEW.catagory;
    
    END;
    

    Not sure if its the optimal solution but it works and allows me to keep track of image numbers in catagories for each parent object.

提交回复
热议问题