简体   繁体   中英

MySQL AUTO_INCREMENT by group using InnoDB or alternatives

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM