【问题标题】:database with Category, (Optional subcategory) and sub-subcategory (service)具有类别、(可选子类别)和子子类别(服务)的数据库
【发布时间】:2018-10-01 17:03:48
【问题描述】:

以为我一个人就能搞定,但是……我觉得我浪费了太多时间…… 大家好!我正在为 Room 数据库结构苦苦挣扎——我不确定我的方法是否正确。我想要实现的是能够将服务(子子类别)添加到类别中,但也可能有可选的子类别:

类别 -> 服务

类别 -> 可选子类别 -> 服务

我已经做过的事情(跳过了一些基本的代码部分):

a) 创建实体

@Entity
class Category
int id
String name

@Entity
class Subcategory
int id
String name
int categoryID

@Entity
class Subcategory
int id
String name
int categoryID
int subcategoryID

b) 创建连接表

@Entity
class Join
int id
int categoryID
int subcategoryID
int serviceID

当一个类别包含任何服务的子类别时,这很简单:

id | categoryId | SubcategoryId| ServiceId|
-------------------------------------------
1  |          1 |            1 |        1 |
1  |          1 |            1 |        2 |

但如果没有子类别并且服务仅属于类别:

id | categoryId | SubcategoryId| ServiceId|
-------------------------------------------
1  |          1 |         null |        1 |

我将null 设置为 SubcategoryId 并检查 subcategory 是否为空

所以问题是:这种方法在关系数据库设计方面是否正确?

或者我应该: 1. 创建category-subcategory、subcategory-service、category-service 连接表并最终以某种方式将它们连接成一个大连接? 2.还是在服务中添加categoryId和subcategoryId?

非常感谢任何 cmets、提示和技巧! :)

【问题讨论】:

    标签: android database-design android-room


    【解决方案1】:

    而不是将其加入到其他关系表中,我会使用以下方法:

    假设您只有两个类别,一个是主要(主类别),第二个是次要类别(子类别)

    我会像这样在单个表中为 Category 创建实体:

    @Entity
    class Category
    int id // It's our primary key here
    String name
    int parentId // To detect if category is Main/Sub. How? "Null" if Main, "main category" id if child
    

    现在关于Service实体:

    @Entity
    class Service
    int id
    String name
    //This is our foreign key from Category table
    int categoryId //It can be Main/Sub category id from "Category" Table, how to detect it's Main/Sub? Check it from category table using "parentId".
    

    为什么采用这种方法?

    因为,

    1 Service 依赖于 Category,因此 Service 无关紧要 类别是否是主/子。它所知道的只是它的类别 本身。

    2 现在是类别,为什么没有单独的表? 因为,即使它是子类别,我们也需要像对待它们一样对待它们 类别(确实如此),因此最好将其视为类别和 通过一个名为 parentId 的新参数来区分两者。

    【讨论】:

    • 谢谢大家的回复。在做了一些深入的研究之后,我决定使用@Jeel Vankhede 所谓的邻接列表模型——工作得很好,而且这次似乎比嵌套集更适合我的 db 结构:)
    【解决方案2】:

    有一种旧的设计叫做嵌套集。这种设计的优点是比较简单,可以创建任意深度的类别和子类别。查询速度很快,可以通过多种方式检索数据:例如,显示某个类别的第 4 级子类别。

    一个缺点是查询有些复杂,但是一旦您克服了学习曲线,就会非常直观。

    另一个缺点是 DML 非常昂贵,因此这仅在数据一旦建立后非常稳定时才有用。

    如果这似乎符合您的需求,我会在 this answer 中提供更多详细信息以及大量示例代码。

    【讨论】:

      猜你喜欢
      • 2019-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-14
      • 2015-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多