There is a page on which categories are displayed (Fig. See below). enter image description here

Interested in the question:
Is there an easier way to store categories than the one I came up with (see below)? There is a table in which these categories are stored.

ID Name Position Link 1 Авто 01-00-00 2 Грузовые 01-01-00 3 Маз 01-01-01 4 Камаз 01-01-02 5 Легковые 01-02-00 6 Газ 01-02-01 7 Заз 01-02-02 8 Книги 02-00-00 9 Зарубежные 02-01-00 10 К.Дойл 02-01-01 11 М.Твен 02-01-02 

Etc.
Those. The first 2 digits are the number of basic categories, the second two and the third two are the number of subcategories.
This is all due to the fact that later in html I will have to distribute this array ..., i.e. making a loop on it, I will apply certain html-tags to each of these categories.

    2 answers 2

    One of the options is a tree structure of objects.

    But if you intend to store only three levels of nesting (categories, subcategories, objects). That your decision has the right to exist. The only thing you need to split the position column into three different columns.

    Also, try to analyze whether two connections are one to many (from an architectural point of view, it looks more natural with your subject area), something like this:

     Category (id, name) SubCategory (id, categoryId, name) Objects (id, subCategoryId, name) 

    Perhaps with some supporting information, the structure of which may differ in different tables.

      Instead of generating such a serial number and then parsing, it is better to put the links in a separate table (for example ) or create a link to the "parent" for the child records (then it will be null for the root elements).

      To determine the level of nesting, you need to add a level column to the table. In your example, it will look like this:

       ID ParentId level Name Link 1 null 1 Авто 2 1 2 Грузовые 3 2 3 Маз 4 2 3 Камаз 5 1 2 Легковые 6 5 3 Газ 7 5 3 Заз 8 null 1 Книги 9 8 2 Зарубежные 10 9 3 К.Дойл 11 9 3 М.Твен 

      Some examples of implementation can be found here .

      PS In principle, this is a trivial task of storing a tree structure in a database.

      • Better just think a link to the parent of the child. The table of relations is always a great confusion, and that which has to be raked. - Goncharov Alexander
      • I would have done so, but I don’t know what kind of nesting will be, and to create a new table for each nesting .... - Konstantin78
      • @ Konstantin78, the examples I work with any number of nesting levels without creating an N-th number of additional tables. In the first method, only one table is created that stores only information about links, no more. - Streletz