MySQL: Grouped primary key with InnoDB

后端 未结 2 452
长情又很酷
长情又很酷 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.

    0 讨论(0)
  • 2021-01-24 02:55

    there can be only one auto column and it must be defined as a key. check this

    
    CREATE TABLE images (
       parent_id INT(11) NOT NULL,
       image_id INT(11) Not Null  AUTO_INCREMENT, 
       source_url VARCHAR(255) NOT NULL,
       caption VARCHAR(255) NOT NULL,
    
       key(image_id),                          -- add as a key       
       PRIMARY KEY(parent_id, image_id)
    ) ENGINE = InnoDB;
    
    0 讨论(0)
提交回复
热议问题