具有单个默认子项的数据库模型父子项。

发布于 2025-01-03 09:36:55 字数 338 浏览 1 评论 0原文

是否有一种最佳实践模式来模拟以下父子关系,其中可以将一个子项标记为默认子项。

我可以想到两种方法。哪个更好或者还有其他更好的替代方案?

   - ParentTable
      - Id

   - ChildTable
      - Id
      - ParentId
      - IsDefault

或者

   - ParentTable
      - Id
      - DefaultChildId

   - ChildTable
      - Id
      - ParentId

Is there a best practice pattern to model the following parent child relationship where exactly one child can be flagged as the default child.

I can think of two ways. Which is better or is there another better alternate?

   - ParentTable
      - Id

   - ChildTable
      - Id
      - ParentId
      - IsDefault

or

   - ParentTable
      - Id
      - DefaultChildId

   - ChildTable
      - Id
      - ParentId

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柏拉图鍀咏恒 2025-01-10 09:36:55

我赞成完全防止无效数据存在的数据模型。如果您使用第二种方法并在 DefaultChildId 和 ChildTable 之间创建外键关系,那么您可以添加约束以确保您的数据库永远不会处于无效状态 - 例如,如果您尝试删除一个子项是某人的默认子项,数据库会阻止您。使用第一种方法,不会。

具体来说(如评论中所述),应在 DefaultChildId 上使用 ON DELETE RESTRICT 约束,并在 ParentID 上使用 ON DELETE CASCADE 约束。这允许更灵活地创建记录(您不需要已有默认子项即可创建父项),防止在未先更新到新默认值的情况下意外删除默认子项,并智能地处理删除父母。

I favor data models that prevent invalid data from existing at all. If you use the second approach and create a foreign key relationship between DefaultChildId and the ChildTable, then you can add constraints to ensure that your database can't ever be in an invalid state -- if you try to, say, delete a child that is somebody's default child, the database will prevent you. Using the first approach, it won't.

Specifically (as noted in a comment), ON DELETE RESTRICT constraint should be used on DefaultChildId and ON DELETE CASCADE on ParentID. This allows creation of records with more flexibility (you don't need to have a default child already there to be able to make a parent), prevents accidental deletion of default child without first updating to a new default, and intelligently handles deletion of the parent.

沧笙踏歌 2025-01-10 09:36:55

一般来说,第二个更好,因为它更容易确保一个且只有一个子级是默认子级。

SQL也比较

一点

SELECT * 
FROM   parenttable p 
       INNER JOIN childtable c 
         ON p.id = c.parentid 
            AND c.isdefault = 1 

清晰

SELECT * 
 FROM   parenttable p 
     INNER JOIN childtable c 
       ON p.defaultchildid = c.id 

Generally speaking the second one is better since its easier to ensure that one and only one child is the default child.

The SQL is also a slightly clearer

Compare

SELECT * 
FROM   parenttable p 
       INNER JOIN childtable c 
         ON p.id = c.parentid 
            AND c.isdefault = 1 

vs

SELECT * 
 FROM   parenttable p 
     INNER JOIN childtable c 
       ON p.defaultchildid = c.id 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文