在 MySQL 中定义具有自动增量的复合键

场景:

我有一个引用两个外键的表,对于这些外键的每个唯一组合,都有自己的 auto_increment 列.我需要实现一个复合键,以帮助使用这三者的组合(一个外键和一个 auto_increment 列,以及另一个具有非唯一值的列)将行标识为唯一的

I have a table which references two foreign keys, and for each unique combination of these foreign keys, has its own auto_increment column. I need to implement a Composite Key that will help identify the row as unique using combination of these three (one foreign keys and one auto_increment column, and one other column with non-unique values)

表格:

CREATE  TABLE `issue_log` (
`sr_no` INT NOT NULL AUTO_INCREMENT ,
  `app_id` INT NOT NULL ,
  `test_id` INT NOT NULL ,
  `issue_name` VARCHAR(255) NOT NULL ,
primary key (app_id, test_id,sr_no)
);

当然,我的查询肯定有问题,因此抛出的错误是:

Of course, there has to be something wrong with my query, because of which the error thrown is:

ERROR 1075:表定义不正确;只能有一辆汽车列,必须定义为键

ERROR 1075: Incorrect table definition; there can be only one auto column and it must be defined as a key

我想要达到的目标:

我有一个应用程序表(以 app_id 作为其主键),每个应用程序都有一组要解决的问题,每个应用程序都有多个测试(因此 test_id col)sr_no col 应该为唯一的 app_id 和 test_id 增加.

I have an Application Table (with app_id as its primary key), each Application has a set of Issues to be resolved, and each Application has multiple number of tests (so the test_id col) The sr_no col should increment for unique app_id and test_id.

即表中的数据应如下所示:

i.e. The data in table should look like:

数据库引擎是 InnoDB.我想以尽可能简单的方式实现这一点(即,如果可能,请避免触发器/程序 - 建议用于其他问题的类似案例).

The database engine is InnoDB. I want to achieve this with as much simplicity as possible (i.e. avoid triggers/procedures if possible - which was suggested for similar cases on other Questions).

推荐答案

对于 InnoDB 表,您不能让 MySQL 自动为您执行此操作 - 您需要使用触发器或过程,或者使用其他数据库引擎,例如 MyISAM.只能对单个主键进行自动递增.

You can't have MySQL do this for you automatically for InnoDB tables - you would need to use a trigger or procedure, or user another DB engine such as MyISAM. Auto incrementing can only be done for a single primary key.

类似下面的东西应该可以工作

Something like the following should work

DELIMITER $$

CREATE TRIGGER xxx BEFORE INSERT ON issue_log
FOR EACH ROW BEGIN
    SET NEW.sr_no = (
       SELECT IFNULL(MAX(sr_no), 0) + 1
       FROM issue_log
       WHERE app_id  = NEW.app_id
         AND test_id = NEW.test_id
    );
END $$

DELIMITER ;

相关文章