Mysql 客户自动递增

Mysql auto-increment by customer

我有一个 table Invoices,其中有一些字段,例如 InvoiceIdCustomerNumber 我希望字段 Number 自动递增,但每个 customer 这是它看起来像的一个例子 例如

InvoiceId| Customer| Number
:------- | ------: | :----:
258      | A       | 1
2568     | B       | 1
85475    | B       | 2
63       | B       | 3
64       | A       | 2
65       | B       | 4
67       | C       | 1

这似乎是可能的only using MyISAM storage engine:

MyISAM Notes

For MyISAM tables, you can specify AUTO_INCREMENT on a secondary column in a multiple-column index. In this case, the generated value for the AUTO_INCREMENT column is calculated as MAX(auto_increment_column) + 1 WHERE prefix=given-prefix. This is useful when you want to put data into ordered groups.

CREATE TABLE animals (
    grp ENUM('fish','mammal','bird') NOT NULL,
    id MEDIUMINT NOT NULL AUTO_INCREMENT,
    name CHAR(30) NOT NULL,
    PRIMARY KEY (grp,id)
) ENGINE=MyISAM;

INSERT INTO animals (grp,name) VALUES
    ('mammal','dog'),('mammal','cat'),
    ('bird','penguin'),('fish','lax'),('mammal','whale'),
    ('bird','ostrich');

SELECT * FROM animals ORDER BY grp,id;

Which returns:

+--------+----+---------+
| grp    | id | name    |
+--------+----+---------+
| fish   |  1 | lax     |
| mammal |  1 | dog     |
| mammal |  2 | cat     |
| mammal |  3 | whale   |
| bird   |  1 | penguin |
| bird   |  2 | ostrich |
+--------+----+---------+

In this case (when the AUTO_INCREMENT column is part of a multiple-column index), AUTO_INCREMENT values are reused if you delete the row with the biggest AUTO_INCREMENT value in any group. This happens even for MyISAM tables, for which AUTO_INCREMENT values normally are not reused.

强调我的。

因此,如果您使用不同的存储引擎,则需要手动生成序列 ID。

ALTER TABLE tablename CHANGE number number INT(11) AUTO_INCREMENT PRIMARY KEY;

如果更改无效,请尝试修改