Search code examples
mysqlkeycomposite

Composite Primary Key and Auto_Increment


I'm trying to do the composite key with one of them auto incrementing, but when I try to enter a new row it just continue the sequential.

Here's the example of what happens:

Item_1 | Item_2
1     |   1    
1     |   2
2     |   3
2     |   4
2     |   5

Here's the example of what I want:

Item_1 | Item_2
1     |   1    
1     |   2
2     |   1
2     |   2
2     |   3

I create the table this way:

CREATE TABLE IF NOT EXISTS `usuarios` (
  `cod_user` int(11) NOT NULL AUTO_INCREMENT,
  `cod_user_emp` int(11) NOT NULL,
  PRIMARY KEY (`cod_user`,`cod_user_emp`),
  UNIQUE KEY `user` (`user`),
  KEY `cod_user` (`cod_user`)
  );

Edit

I resolved the problem doing a server sided php validation.

$result = $db->query("SELECT * FROM usuarios WHERE cod_user_emp=\"$emp\" ORDER BY cod_user DESC LIMIT 1");
while($row=$result->fetch_array()){
   $cod2 = $row['cod_user']+1;
}

Solution

  • Remove that AUTO_INCREMENT column,

    CREATE TABLE IF NOT EXISTS `usuarios` 
    (
      `cod_user` int(11) NOT NULL,
      `cod_user_emp` int(11) NOT NULL,
      PRIMARY KEY (`cod_user`,`cod_user_emp`) -- <<== this is enough
    );
    

    And can create a Stored Procedure that increments Item_2 for every Item_1.

    DELIMITER $$
    CREATE PROCEDURE InsertRecord(IN ItemA INT)
    BEGIN
        SET @max_id =  (
                        SELECT COALESCE(MAX(Item_2), 0) + 1
                        FROM TableName
                        WHERE   Item_1 = ItemA
                        );
        INSERT INTO tableName(Item_1, Item_2)
        VALUES(ItemA, @max_id)
    END $$
    DELIMITER ;
    

    and call it like this,

    CALL InsertRecord(2);