简体   繁体   English

创建Sql子类别表

[英]Create Sql subcategory table

I have went to give interview today there is question that i didn't hear about, i wana know how to do this ... how to make this with query 我今天去接受采访,有一个我未曾听说过的问题,我想知道该如何做...如何通过查询来做到这一点

create a single table that can hold up till n-level category's. 创建一个可以容纳n级类别的表。 create a table to expandable category tree given the following example . 给出以下示例,为可扩展类别树创建一个表。 Now the table should be designed in such way that category level can be extended to as much as required . 现在,表的设计应使类别级别可以扩展到所需的程度。

                                  root
                                  /   \
                                 /     \
                               MEN      women------------
                               / \         /            |
                              /   \       Shirt&top     paints
                         shirt   trousers                /   \ 
                                                        /     \
                                                       /       \
                                                      /         \
                                                    trouser     Skirts and jeans

The "cookbook" solution would be to have a parent id column pointing to a category id in a single table: “烹饪书”解决方案将是在单个表中具有指向类别ID的父ID列:

CREATE TABLE categories (
    category_id INT PRIMARY KEY,
    parent_id INT REFERENCES category_id,
    name VARCHAR(100)
)

So, for the example given above: 因此,对于上面给出的示例:

INSERT INTO categories VALUES (1, null, 'root'),
(2, 1, 'Men'),
(3, 2, 'shirt'),
(4, 2, 'trousers'),
(5, 1, 'women'),
(6, 5, 'shirt & top'),
(7, 5, 'pants'),
(8, 7, 'trousers'),
(9, 7, 'skirts and jeans');

If you need to implement that structure in a single table, you could store per row the following information: 如果需要在单个表中实现该结构,则可以每行存储以下信息:

  1. id (primary key, category id) ID(主键,类别ID)
  2. parent_id (points to the parent category id) parent_id(指向父类别ID)
  3. category_name (textual representation of the category name) category_name(类别名称的文字表示)

So in your example, the data would be stored as such: 因此,在您的示例中,数据将这样存储:

1 | 0 | root
2 | 1 | MEN
3 | 2 | shirt
4 | 2 | trousers
5 | 1 | women
6 | 5 | shirt & top

... and so on ... 等等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM