Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 自动递增复合键InnoDB_Mysql_Innodb - Fatal编程技术网

Mysql 自动递增复合键InnoDB

Mysql 自动递增复合键InnoDB,mysql,innodb,Mysql,Innodb,我想为InnoDB MySQL表创建类似MyISAM的行为。我想要一个复合主键: 主键(id1、id2) 其中id1基于id2的值自动递增。使用InnoDB实现这一目标的最佳方式是什么 +----------+-------------+--------------+ | id1 | id2 | other_column | +----------+-------------+--------------+ | 1 | 1 | Foo

我想为InnoDB MySQL表创建类似MyISAM的行为。我想要一个复合主键:

主键(id1、id2)

其中id1基于id2的值自动递增。使用InnoDB实现这一目标的最佳方式是什么

+----------+-------------+--------------+
|      id1 |         id2 | other_column |
+----------+-------------+--------------+
|        1 |           1 | Foo          |
|        1 |           2 | Bar          |
|        1 |           3 | Bam          |
|        2 |           1 | Baz          |
|        2 |           2 | Zam          |
|        3 |           1 | Zoo          |
+----------+-------------+--------------+

您可以使用此插入前触发器替换零id值-

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
然后插入零值(id1或id2)以生成新值-

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');
...

您所说的“其中id1根据id2的值自动递增”是什么意思?请参阅发布的示例数据。这就是我想要的行为。你可以做很多工作来实现这样的目标。它将是缓慢的片状和脆弱的。这应该是两个表或一个单值键。因此id2是手动插入的,只有在主键冲突时id1才会递增?为什么要这样做?