问题
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:
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.
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.
I could probably use a sequence, but I think that would be ugly to maintain a separate sequence for every user.
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