如何设计有父子关系的DB?
如果我需要在数据库中表示位置(例如国家、州/省/地区、城市等),我将如何以最容易查询、最大程度扩展等方式进行操作.?我计划将其用于一个应用程序,该应用程序将允许用户选择多个位置并将它们关联到他们的个人资料。
我想到的解决方案是这样的:
===========================
| Id | ParentId | Name |
===========================
| 1 | 0 | USA |
---------------------------
| 2 | 1 | Alabama |
---------------------------
我想知道这样的解决方案是否存在任何潜在的问题。谢谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您知道不同类型的项目(城邦国家),则应该创建单独的表。将它们全部放在一张表中会使查询变得更加困难。
如果您使用不同的表类型,则可以强制引用完整性,这样就不会出现孤表。
为孩子们想想吧!
If you know the different types of items (city state countries), you should create separate tables. Putting them all in one table will make it more difficult to query.
If you use different table types, you can enforce referential integrity, so you don't get orphans.
Think about the children!
这似乎相当适合可扩展性,但是我可能会包含一个附加列来标识实际的行/条目(如果愿意的话,实体的类型)。
这将允许您根据选择(国家、城市等)轻松查询。您可能会发现,层级结构可能会给您带来一些痛苦,因为整个结构都在一个表中,并且您不知道开始的深度。
最终,设计将取决于您可能拥有的已知子部分数量,以及这种标准化实际上是否会使生活变得更加困难,而不是不会。
This seems fairly suitable to scalability, I might however include an additional column to identify the actual row/entry (type of entity if you will).
This will allow you to easily query based on selection (country, city, etc.). You might find though that the hiracrchy can cause you some pain, seeing as the entire structure will be in a single table, and you do not know the depth to start with.
In the end, the design will depend on the known number of sub sections you might have, and wether such normalization might in fact make life more diffucult, rather than not.
根据您的受众,您可能还需要考虑按类型分离名称值,以便可以在不重复层次结构的情况下本地化它们。
Depending on your audience, you may also want to consider separating out the name values by type so they can be localized without duplicating the hierarchical structure.
我使用类似的东西并且取得了很大的成功。最近的我的问题可能会派上用场。
在某些情况下(例如这种)我不想绑定到表结构。自我引用可能是一件很棒的事情。我不明白为什么在代码中使用相同对象类型的树状结构是如此可接受,但在涉及数据库时程序员却回避它。
I use something similar and have had much success with it. A recent Question of mine might come in handy.
In some cases (such as this) I dont want to be tied to a table structure. Self referencing can be a great thing. I dont understand why it's so acceptable to have tree-like structures using the same object type in code, but its shunned by programmers when it comes to databases.