Interesting tree/hierarchical data structure problem

后端 未结 6 903
無奈伤痛
無奈伤痛 2020-12-16 05:24

Colleges have different ways of organizing their departments. Some schools go School -> Term -> Department. Others have steps in between, with the longe

6条回答
  •  清歌不尽
    2020-12-16 05:45

    I would develop this in a very flexible manner and what seems to mean to be the simplest as well:

    There should only be one table, lets call it the category_nodes:

    -- possible content, of this could be stored in another table and create a
    -- 1:N -> category:content relationship
    drop table if exists category_nodes;
    create table category_nodes (
      category_node_id int(11) default null auto_increment,
      parent_id int(11) not null default 1,
      name varchar(256),
      primary key(category_node_id)
    );
    -- set the first 2 records:
    insert into category_nodes (parent_id, name) values( -1, 'root' );
    insert into category_nodes (parent_id, name) values( -1, 'uncategorized' );
    

    So each record in the table has a unique id, a parent id, and a name.

    Now after the first 2 inserts: in category_nodes where the category_node_id is 0 is the root node (the parent of all nodes no matter how many degres away. The second is just for a little helper, set an uncategorized node at the category_node_id = 1 which is also the defalt value of parent_id when inserting into the table.

    Now imagining the root categories are School, Term, and Dept you would:

    insert into category_nodes ( parent_id, name ) values ( 0, 'School' );
    insert into category_nodes ( parent_id, name ) values ( 0, 'Term' );
    insert into category_nodes ( parent_id, name ) values ( 0, 'Dept' );
    

    Then to get all the root categories:

    select * from category_nodes where parent_id = 0;
    

    Now imagining a more complex schema:

    -- School -> Division -> Department
    -- CatX -> CatY
    insert into category_nodes ( parent_id, name ) values ( 0, 'School' ); -- imaging gets pkey = 2 
    insert into category_nodes ( parent_id, name ) values ( 2, 'Division' ); -- imaging gets pkey = 3
    insert into category_nodes ( parent_id, name ) values ( 3, 'Dept' );
    --
    insert into category_nodes ( parent_id, name ) values ( 0, 'CatX' ); -- 5
    insert into category_nodes ( parent_id, name ) values ( 5, 'CatY' );
    

    Now to get all the subcategories of School for example:

    select * from category_nodes where parent_id = 2;
    -- or even
    select * from category_nodes where parent_id in ( select category_node_id from category_nodes 
        where name = 'School'
    );
    

    And so on. Thanks to a default = 1 with the parent_id, inserting into the 'uncategorized' category become simple:

    Cheers

提交回复
热议问题