Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto Increment Composite Key InnoDB

Tags:

mysql

innodb

I want to create a MyISAM like behavior for an InnoDB MySQL table. I want to have a composite primary key:

PRIMARY KEY(id1, id2)

Where id1 auto increments based on the value of id2. What's the best way to accomplish this with InnoDB?

+----------+-------------+--------------+
|      id1 |         id2 | other_column |
+----------+-------------+--------------+
|        1 |           1 | Foo          |
|        1 |           2 | Bar          |
|        1 |           3 | Bam          |
|        2 |           1 | Baz          |
|        2 |           2 | Zam          |
|        3 |           1 | Zoo          |
+----------+-------------+--------------+
like image 835
CaptainStiggz Avatar asked Aug 15 '12 11:08

CaptainStiggz


People also ask

Is it possible to set a foreign key as auto increment?

When creating a table, there is an option for us to set the numeric primary key as autoincrement where its value increases whenever a new data in inserted. This primary number can be used for setting the relationship of a table where it is assigned as a foreign key to that table.

Does auto increment have to be primary key?

AUTO_INCREMENT columns start from 1 by default. The automatically generated value can never be lower than 0. Each table can have only one AUTO_INCREMENT column. It must defined as a key (not necessarily the PRIMARY KEY or UNIQUE key).

What is engine InnoDB AUTO_INCREMENT?

1.6 AUTO_INCREMENT Handling in InnoDB. InnoDB provides a configurable locking mechanism that can significantly improve scalability and performance of SQL statements that add rows to tables with AUTO_INCREMENT columns.

Does MySQL auto increment primary key?

The Auto Increment feature allows you to set the MySQL Auto Increment Primary Key field. This automatically generates a sequence of unique numbers whenever a new row of data is inserted into the table.


1 Answers

You can use this BEFORE INSERT trigger to substitute zero id-values -

CREATE TRIGGER trigger1
  BEFORE INSERT
  ON table1
  FOR EACH ROW
BEGIN

  SET @id1 = NULL;

  IF NEW.id1 = 0 THEN
    SELECT COALESCE(MAX(id1) + 1, 1) INTO @id1 FROM table1;
    SET NEW.id1 = @id1;
  END IF;

  IF NEW.id2 = 0 THEN

    IF @id1 IS NOT NULL THEN
      SET NEW.id2 = 1;
    ELSE
      SELECT COALESCE(MAX(id2) + 1, 1) INTO @id2 FROM table1 WHERE id1 = NEW.id1;
      SET NEW.id2 = @id2;
    END IF;

  END IF;

END

Then insert zero-values (id1 or id2) to generate new values -

INSERT INTO table7 VALUES(0, 0, '1');
INSERT INTO table7 VALUES(0, 0, '2');
INSERT INTO table7 VALUES(1, 0, '3');
INSERT INTO table7 VALUES(1, 0, '4');
INSERT INTO table7 VALUES(1, 0, '5');
...
like image 152
Devart Avatar answered Sep 28 '22 08:09

Devart