开发者

root in tree like structure with auto-referencing foreign keys

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_fo开发者_C百科lder)
  • 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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜