1个auto_increment,带2个主键

时间:2015-05-13 08:36:42

标签: mysql primary-key innodb auto-increment myisam

我的目的是创建一个包含2个主键的表,其中一个是自动增量,另一个是在插入时指定的,当我为该表创建一个新字段时,如果未增加的主键发生更改,则必须启动重新计数。这就是我所拥有的:

我已经能够将表引擎更改为MyISAM。但是缺少一些东西,auto_increment并没有像以前那样从100开始。

CREATE TABLE CONFIGURABLES(
    CODIEI2 INTEGER AUTO_INCREMENT,
    CODIEI1 INTEGER,
    SKU VARCHAR(30),
    COLOR INTEGER,
    COLOR2 INTEGER,
    TALLA INTEGER,
    CONSTRAINT PK_CODIEI PRIMARY KEY(CODIEI1,CODIEI2),
    CONSTRAINT FK_CODIEI1 FOREIGN KEY(CODIEI1) REFERENCES PRODUCTOS(ENTITY_ID) ON DELETE CASCADE,
    CONSTRAINT FK_CCOLOR FOREIGN KEY(COLOR) REFERENCES COLORES(CODICOL) ON DELETE CASCADE,
    CONSTRAINT FK_CCOLOR2 FOREIGN KEY(COLOR2) REFERENCES COLORES(CODICOL) ON DELETE CASCADE,
    CONSTRAINT FK_CTALLA FOREIGN KEY(TALLA) REFERENCES TALLAS(CODITLL) ON DELETE CASCADE) ENGINE=MyISAM;

ALTER TABLE CONFIGURABLES AUTO_INCREMENT = 100;

是否发生这种情况,因为当auto_increment值与默认数字不同时,引擎必须设置为InnoDB?

有没有办法按我的意愿得到它?

SOLUTION:

该表可以返回到InnoDB,它更好,并且auto_increment表上不需要CONFIGURABLES,因为在执行插入时这将被控制。

CREATE TABLE CONFIGURABLES(
    CODIEI2 INTEGER,
    CODIEI1 INTEGER,
    SKU VARCHAR(30),
    COLOR INTEGER,
    COLOR2 INTEGER,
    TALLA INTEGER,
    CONSTRAINT PK_CODIEI PRIMARY KEY(CODIEI1,CODIEI2),
    CONSTRAINT FK_CODIEI1 FOREIGN KEY(CODIEI1) REFERENCES PRODUCTOS(ENTITY_ID) ON DELETE CASCADE,
    CONSTRAINT FK_CCOLOR FOREIGN KEY(COLOR) REFERENCES COLORES(CODICOL) ON DELETE CASCADE,
    CONSTRAINT FK_CCOLOR2 FOREIGN KEY(COLOR2) REFERENCES COLORES(CODICOL) ON DELETE CASCADE,
    CONSTRAINT FK_CTALLA FOREIGN KEY(TALLA) REFERENCES TALLAS(CODITLL) ON DELETE CASCADE);

在插入时执行此操作:

BEGIN;
    SELECT @id := IFNULL(MAX(CODIEI2)+1,100) FROM CONFIGURABLES WHERE CODIEI1 = 10001 FOR UPDATE;
    INSERT INTO CONFIGURABLES
    (CODIEI1,CODIEI2,SKU,COLOR,COLOR2,TALLA)
    VALUES
    (10001,@id,'',4,2,2);
COMMIT;

2 个答案:

答案 0 :(得分:1)

  BEGIN;
  SELECT @id := MAX(id)+1 FROM foo WHERE other = 123 FOR UPDATE;
  INSERT INTO foo
     (other, id, ...)
     VALUES
     (123, @id, ...);
  COMMIT;

答案 1 :(得分:0)

如何插入数据?如果您将CODIEI2作为列和值给出,则会覆盖auto_increment。

在SQLFiddle中测试:

构建架构:

CREATE TABLE CONFIGURABLES(
CODIEI2 INTEGER AUTO_INCREMENT,
CODIEI1 INTEGER,
CONSTRAINT PK_CODIEI PRIMARY KEY(CODIEI2));

ALTER TABLE CONFIGURABLES AUTO_INCREMENT = 100;

INSERT INTO CONFIGURABLES ( CODIEI1 ) 
VALUES ( 1 );

现在覆盖auto_increment:

INSERT INTO CONFIGURABLES ( CODIEI2, CODIEI1 ) 
VALUES ( 1, 2 );

运行SQL:

SELECT *
FROM CONFIGURABLES;

输出:

CODIEI2 CODIEI1
1   2
100 1