MySQL AUTO_INCREMENT by group using InnoDB or alternatives

こ雲淡風輕ζ 提交于 2020-01-15 09:01:09

问题


I am designing a web application using a MySQL database, and I am stuck on one of the fine points of my database design.

Here's an example of the type of data I would like to store using the InnoDB engine:

user_id   account_id
1         1
1         2
1         3
2         1
2         2
3         1

As is clear from the above, I would like the account_id to auto increment for each individual user. Here are some problems I have encountered:

  1. I do know that to do this automatically I could use the MyISAM engine, but after I have done some reading, I have come to the realization that when updates happen, this engine will lock the whole table instead of just one row. This is no good to me. Also, MyISAM does not enforce referential integrity, which I would highly like to keep.

  2. I have read other people's solutions to this problem, and they have used a trigger. I could, of course, use a trigger, but I am not very fond of triggers, as they are more difficult to maintain than just one table.

  3. I could probably use a sequence, but I think that would be ugly to maintain a separate sequence for every user.

  4. I could simply use a unique AUTO_INCREMENT without any regard to the user_id, which would work very well. There are two things about this I do not like: 1. This way, my smallint would potentially grow to int or bigint, which would require a lot MORE storage space. I know that storage space is cheap, but I would still like to minimize it. 2. It would be much cleaner to auto increment by group.

I would like to get some feedback/opinions of those users that have encountered and successfully solved this problem. Perhaps, there is another solution that I haven't thought of. Perhaps, there is another way to organize my table that I haven't thought of.


回答1:


Use a simple AUTO_INCREMENT and ignore the storage:

  • If you scale to a million users, each having 1000 accounts, you will need approx. 3MB of additional storage.
  • The performance benefit of a single-field primary index (mostly sorted in real storage!) will be worth much more, than that bit of storage


来源:https://stackoverflow.com/questions/9381734/mysql-auto-increment-by-group-using-innodb-or-alternatives

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