具有自动引用外键的树状结构的根

发布于 2024-09-14 05:57:17 字数 342 浏览 4 评论 0原文

我的应用程序使用某种“虚拟文件夹”,因此我需要将树结构存储在数据库中。保存数据的表非常简单,它有 3 列:

  • id_folder (int,primary key)
  • id_parent (int,references id_folder)
  • folder_name (string)

我的问题是:哪种是实现根的最佳方法?

  1. 使 id_parent 可以为空;根目录将是 id_parent=null 的文件夹,或者
  2. 使该文件夹成为其自己的父文件夹,即 id_folder=id_parent。

谢谢。

My application uses some kind of "virtual folders" so I need to store the tree structure in the database. The table holding the data is quite simple, it has 3 columns:

  • id_folder (int, primary key)
  • id_parent (int, references id_folder)
  • folder_name (string)

My question is: which is the best way to implement the root?

  1. Making id_parent nullable; the root will be the folder with id_parent=null, or
  2. Making the folder to be its own parent, i.e., id_folder=id_parent.

Thank you.

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

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

发布评论

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

评论(2

何止钟意 2024-09-21 05:57:17

我赞成选项 1。

如果您选择选项 2,那么显示子文件夹的逻辑将需要进行令人困惑的检查,以确保 id_folder 和 id_parent 不匹配。

选项 1:

SELECT * --don't kill me for using *, it's just for an example
FROM Folders
WHERE id_parent = @folderId

选项 2:

SELECT * --don't kill me for using *, it's just for an example
FROM Folders
WHERE id_parent = @folderId AND id_parent <> id_folder

I would argue for option 1.

If you choose option 2, then your logic for displaying sub-folders would need confusing checks to make sure that the id_folder and id_parent don't match.

Option 1:

SELECT * --don't kill me for using *, it's just for an example
FROM Folders
WHERE id_parent = @folderId

Option 2:

SELECT * --don't kill me for using *, it's just for an example
FROM Folders
WHERE id_parent = @folderId AND id_parent <> id_folder
简单 2024-09-21 05:57:17

这实际上取决于您是否有其他要求。我喜欢 NULL,因为它具有逻辑意义,但其他要求可能需要其他东西。

It really depends on whether you have additional requirements. I like NULL, as it makes logical sense, but other requirements may call for something else.

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