简体   繁体   中英

The best/correct way in MySql to group records (not “Group By”)

I have a table that is going to have a bunch of stock numbers and some other information. I need to be able to create groups of stock numbers eg products 123A,456B, and 789C all are in the same group. Each stock number has its own record in the table. I don't really care how it is accomplished so long as I can make sure that the items are grouped and that group numbers are unique. What is the best way to accomplish this?

There are a few ways I can think of to accomplish this but I'm not really sure what the best way is or if there are hidden drawbacks:

1) I could have a separate table with one auto increment column that is responsible for generating group id's and then add the Id to the stock number table once it's generated but that semes wasteful.

2) Would selecting the max groupId from the stock number table and adding one to it be good to get new group id's?

3) I could not have groupId in the stock number table and do it using a separate table with a GroupID column and a StockNumberId column. Still how would I get the groupId doing it this way?

You don't have to respond to all three. In indication of which would be the most appropriate way and any notes on implementation or pitfalls would be helpful. Also if there is a better way I did not innumerate please enlighten me. Thank you.

If you only need to set a groupId for each stock, and if each stock belongs to one and only one group then solution (2) would work just fine.

I would also create an index on the groupId column for easy retrieval of stocks that belong to the same group, as well as for getting the MAX(groupId) more efficiently.

I would use solution (1) if I had to also store group information, eg, groupName, etc.

Solution (3) would be more towards a Many-To-Many relation between Stocks and Groups where the table you are describing sits in between the two. But in your case this would not be a good solution.

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