Constrain a columns value to a value of a different column inside the same table?
I'm creating a tree view for a website using databases. I will create 2 tables, let's call them "Folder" and "File". A folder can contain multiple folders and files, and files will act as leaf nodes - which means they're a "dead end" in the tree if you're unfamiliar with the term.
The folder table will contain columns:
Folder_id, Folder_name, Folder_parent
File will contain:
File_id, File_name, File_parent
Obviously File_parent will reference a folder_id, thus creating a foreign key, but how do I make the Folder_parent reference the Folder_id?
Example:
FOLDER_NAME | FOLDER_ID | FOLDER_PARENT
root 1 null
Cars 开发者_运维问答 2 1
Planes 3 1
BMW 4 2
create table folder (
folder_id int primary key,
folder_name varchar not null,
folder_parent int references folder(folder_id)
)
I would make a separate table to deal with relationships, since a file can easily exist in two folders (think aliases). In this schema, you could simplify things with just a node
table and a relationships
(or edges
, if you're familiar with graph theory) table:
CREATE TABLE nodes (
node_id int primary key,
node_name varchar not null,
node_type enum('folder','file')
)
CREATE TABLE edges (
child_node_id int primary key,
parent_node_id int,
unique( child_node_id, parent_node_id)
)
I'm a little rusty on my sql, so my syntax may need some work, but that's how I would approach it. It's much more flexible this way.
精彩评论