如何与共享相同字段的实体建立数据库关系

时间:2022-12-10 12:53:44

I have two entities, one parent and other child. I have statistics of a parent (count, views, comments), and also I have statistics of parent's child (count, views, comments). Parents and children share the same fields, but they have a relation one to many (one parent has many children).

我有两个实体,一个父母和另一个孩子。我有父母的统计数据(计数,观点,评论),还有父母子女的统计数据(计数,观点,评论)。父母和孩子共享相同的领域,但他们有一对多的关系(一个父母有很多孩子)。

I'm confused about how to model this situation.

我对如何模拟这种情况很困惑。

I'm not sure wheather will be more efficient create two tables and use foreign keys (tables will almost have the same fields, except that child's table will have a parentId).

我不确定wheather会更高效地创建两个表并使用外键(表几乎会有相同的字段,除了child的表将有一个parentId)。

The other situation could be put all data (parent and child) in the same table and try to do an itself relationship.

另一种情况可能是将所有数据(父级和子级)放在同一个表中并尝试建立自己的关系。

Which of this options would be more efficient?

哪个选项更有效?

I'm open to consider others suggestions.

我愿意考虑别人的建议。

Note that this tables will storage millions of records, that will be select later.

请注意,此表将存储数百万条记录,稍后将对其进行选择。

1 个解决方案

#1


2  

Based on your explanation,

根据你的解释,

tables will almost have the same fields, except that child's table will have a parentId

表几乎具有相同的字段,除了子表的将具有parentId

it's better to use Unary Relationship and put parent and child in one Table and use null parentId for parents.

最好使用一元关系并将父和子放在一个表中,并为父项使用null parentId。

But sometimes we can extract some attributes to another table.
If actions on some fields are so much (e.g. so many updates on some fields), it's better to extract them in other table.

但有时我们可以将一些属性提取到另一个表中。如果某些字段上的操作非常多(例如某些字段上有很多更新),最好在其他表中提取它们。

In this case (if you have many actions on these fields), you can put count, views, comments in other table and make a one-to-one relationship between main table.

在这种情况下(如果您对这些字段有许多操作),您可以将计数,视图,注释放在其他表中,并在主表之间建立一对一的关系。

#1


2  

Based on your explanation,

根据你的解释,

tables will almost have the same fields, except that child's table will have a parentId

表几乎具有相同的字段,除了子表的将具有parentId

it's better to use Unary Relationship and put parent and child in one Table and use null parentId for parents.

最好使用一元关系并将父和子放在一个表中,并为父项使用null parentId。

But sometimes we can extract some attributes to another table.
If actions on some fields are so much (e.g. so many updates on some fields), it's better to extract them in other table.

但有时我们可以将一些属性提取到另一个表中。如果某些字段上的操作非常多(例如某些字段上有很多更新),最好在其他表中提取它们。

In this case (if you have many actions on these fields), you can put count, views, comments in other table and make a one-to-one relationship between main table.

在这种情况下(如果您对这些字段有许多操作),您可以将计数,视图,注释放在其他表中,并在主表之间建立一对一的关系。