问题
This is a beginners question about database design. Suppose we have a blogging website with many users, each of whom have a few blog posts. We want to quickly find all articles written by a given user. We could search the post table for all blog posts with the given userID. We could also design the user table to have a list of the user's posts. This would mean, perhaps, storing a string of comma separated post IDs. What is the proper way to do this?
回答1:
You're looking for database normalization, a technique which prevents:
- Redundancy (storing the same data more than once)
- Anomalies (changing one datum changes another)
- Cycles (Changing A changes B which changes C which changes A)
- Redesign (adding or removing a field requires changing other fields)
- Bias (different ways of asking the same question gives different answers)
The typical form of normalization is called Boyce-Codd Normal Form and is, in general, quite difficult to do, but you can improve your design by implementing the lower Normal Forms.
You have not given us enough information to recommend a schema for you, but “storing a string of comma separated post IDs” is the wrong thing to do if you need to distinguish between post IDs. If that’s what you want you should consider a design like:
Users
userID other user fields ..
100 Charlie
101 Edith
Articles
articleID userID pathOrWhatever...
1000 100 http://example.com/stuff
1001 100 http://example.com/moreStuff
1002 101 http://example.com/somethingElse
This design can get articles from users, or users from articles, from database commands.
来源:https://stackoverflow.com/questions/29930453/basic-database-design-list-of-instances-of-type