我想设计像os文件系统, 具体的显示顺序(顺序)可以更新。
我想文件和文件夹可以是同一层, 文件不必在文件夹中。 但在下面的设计中,如果文件不在任何文件夹中我不知道如何保存序列,保存在哪里?
任何建议都是apperciate
数据示例
folder(id:1) top layer: sequence: 0
file(id:1) sequence_in_folder: 0
file(id:2) sequence_in_folder: 1
folder(id:2) top layer: sequence: 1
file(id:3) sequence_in_folder: 0
file(id:4) top layer: sequence: 2 << **sequence save in which table ??**
file(id:5) top layer: sequence: 3 << **sequence save in which table ??**
folder
id sequence parent_folder_id
1 0
2 1
file
id sequence_in_folder folder_id
1 0 1
2 1 1
3 0 2
4 ?????
5 ????
模式
CREATE TABLE IF NOT EXISTS "folder"(
"id" SERIAL NOT NULL,
"sequence" integer NOT NULL,
"parent_folder_id" integer Default NULL,
PRIMARY KEY ("id")
);
CREATE TABLE IF NOT EXISTS "file"(
"id" SERIAL NOT NULL,
"sequence_in_folder" integer Default NULL,
"parent_folder_id" integer NOT NULL,
PRIMARY KEY ("id")
);
更新
基于@Laurenz Albe回答,无需更改表设计,
只需创建一个根文件夹
但是如何通过两个表中的字段交叉/存在来排序数据顺序?
序列存在于文件夹表和文件表中,如何对它们进行排序
查询
SELECT * FROM folder fo
LEFT JOIN file fi ON fi.parent_folder_id = fo.id
WHERE fo.parent_folder_id = $1 AND fi.parent_folder_id = $1
ORDER BY fo.sequence fi.sequence ?? ;
[1]
数据示例
folder
id | sequence | parent_folder_id | name
1 | 0 | | root
2 | 0 | 1 |
3 | 2 | 1 |
file
id | sequence | parent_folder_id |
1 | 1 | 1 |
输出
folder(id:1, sequence:0 name:root)
folder(id:2, sequence:0)
file(id:1, sequence:1)
folder(id:3 sequence:2)
答案 0 :(得分:2)
两个建议:
介绍一个包含所有顶级元素的“匿名”顶级文件夹。
将sequence
的{{1}}列重命名为bookmerk_folder
左右,以避免与max_sequence
混淆。
答案 1 :(得分:1)
Laurenz回答的补充:
统一您的书签和文件夹列,也许是bookmark_node,并要求所有内容都有一个不是书签的父级。像
这样的东西CREATE TABLE IF NOT EXISTS fsnode(
"id" SERIAL NOT NULL,
"name" text,
"is_folder" bool,
"parent_is_folder" bool not null,
"sequence" integer NOT NULL,
"parent_folder_id" integer Default NULL,
CHECK (parent_is_folder),
PRIMARY KEY ("id"),
UNIQUE(id, is_folder), # needed for fkey below
FOREIGN KEY (parent_folder_id, parent_is_folder) REFERENCES fsnode (id, is_folder)
);