Composite Primary Key and Auto_Increment [duplicate]

♀尐吖头ヾ 提交于 2021-02-07 03:46:26

问题


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;
}

回答1:


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


来源:https://stackoverflow.com/questions/15637080/composite-primary-key-and-auto-increment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!