MySQL auto-increment per distinct value entered in other column? [closed]

做~自己de王妃 提交于 2021-02-05 06:53:24

问题


I'd like to create a column in my mysql database which auto increments in response to a specific value being entered into another column.

For example (data below), when a new record is created by a student using the site, he/she would input the name of their class and be assigned a number variable (specific to that class) which could be used by a teacher to identify the student. Is there any way I can do this without creating a new table for each class?

class_name / student_number

classa / 1

classa / 2

classa / 3

classb / 1

classb / 2

classa / 4

classb / 3

回答1:


It seems like you're asking for an auto-increment that maintains a separate increment per distinct value in another column.

As @RickJames answers, this feature exists in the MyISAM storage engine, but it doesn't work in InnoDB. The reason is related to InnoDB's row-level locking: in order to prevent a race condition with another concurrent client inserting to the same 'class' (per your example), InnoDB would have to create a gap lock on all the rows for the given class.

This doesn't affect MyISAM, which does table-level locking anyway, but for InnoDB it would greatly harm throughput during concurrent workloads.

This is not a good reason to use MyISAM.

But you should abandon the idea that an auto-increment is some kind of ordinal or row number—it isn't. All it is is a unique value; it has no other meaning.

If you need to assign consecutive student id's per class, then do so in your application and insert values explicitly. Don't rely on the auto-increment mechanism to do that.




回答2:


MyISAM has such a feature; InnoDB can probably simulate it using a subquery like

( SELECT MAX(student_number) + 1 FROM tbl WHERE class_name = ? )


来源:https://stackoverflow.com/questions/39479880/mysql-auto-increment-per-distinct-value-entered-in-other-column

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