如果我有一个名为动物的类,那么狗和鱼就是子类。
动物有一种属性,叫做“颜色”。
狗有一个叫做“尾巴长度”的属性,而鱼没有这个属性。
鱼有一个属性叫“体重”,狗没有这个属性。
所以,我想设计一个数据库来存储这些信息。我应该怎么办?这里有一些想法:
想法 1:
制作一个动物表,表中有类型,要查找是什么动物,如果是狗,就从狗表中获取结果。
动物:
颜色:绳子
类型:int
类型:
狗:0
鱼:1
狗:
尾长:int
鱼:
重量:int
想法2:
数据库中只存储Dog表和Fish表,删除animal表。
狗:
颜色: 细绳
尾长:int
鱼:
颜色: 细绳
重量:整数
If I have a class called animal, dog and fish is the subclass.
The animal have attribute called "color".
Dog have the attribute called "tail length", and the fish don't have this attribute.
Fish have the attribute called "weight", the dog don't have this attribute.
So, I want to design a database to store this information. What should I do? Here is some ideas:
Idea 1:
Making an animal table, and the table have type, to find what kind of animal, if it is a dog, just get the result from dog table.
Animal:
color:String
type:int
Type:
Dog:0
Fish:1
Dog:
TailLength:int
Fish:
Weight:int
Idea 2:
Store only Dog table and Fish table in the database, remove the animal table.
Dog:
Color: String
TailLength: int
Fish:
Color: String
Weight: int
发布评论
评论(3)
您提到的两种方法:
可以用另外两个来补充:
每种方法都有优点和缺点。这里有一个很好的概述:
另外看看这些SO主题:
最后,应该需要注意的是,有一些面向对象的数据库(又名对象数据库,或 OODBMS)可以更自然地在数据库中表示对象,并且可以轻松解决这个问题,尽管我不认为它们是这样。 re 在行业中经常使用。以下是一些链接,这些链接描述了此类数据库与关系(和其他)数据库的比较,尽管它们不会为您提供关于此事的完全客观(呵呵)观点:
The two approaches you mentioned:
can be supplemented by two others:
Each approach has pros and cons. There's a good rundown of them here:
Also take a look at these SO topics:
Finally, it should be noted that there are object-oriented databases (aka object databases, or OODBMSes) out there that represent objects more naturally in the database, and could easily solve this problem, though I don't think they're as frequently used in the industry. Here are some links that describe such DBs as compared to relational (and other) DBs, though they won't give you an entirely objective (heh) view on the matter:
你可以这样尝试:
这样你就可以为每只动物拥有一个或多个属性(由你选择)。
You could try it like this:
This way you can have one or many attributes per animal (it's up to you to choose).
使用一对零或一对一的关系 正如您所注意到的,在数据库模式设计语言中,表被称为类 - 子类或超类
Use a one to zero or one relationship As you note, In database schema design language the tables are called class - sub-class or superclass