I would refer you to exellent Bill Karwin's book 'SQL Antipatterns' https://pragprog.com/book/bksqla/sql-antipatterns . He has a chapter dedicated to implementing tree like structures in SQL databases (he calls them Naive Trees).
Luckily, this chapter is available to download from Pragratic Programmer's website: http://media.pragprog.com/titles/bksqla/trees.pdf but this excerpt doesn't give you the solution to this problem, but Bill Karwin's blog does: http://karwin.blogspot.com/2010/03/rendering-trees-with-closure-tables.html
The main idea here is to use a separate table Karwin calls a Closure Table. Using the data from another answer here:
drop table if exists brand ;
create table brand (
id int unsigned primary key,
name varchar(100)
);
insert into brand(id, name) values
(1, 'aston martin'),
(2, 'vanquish'),
(3, 'V8'),
(85, '10'),
(6, 'bentley'),
(7, 'continental');
Note that there is no parent_id field here. All the tree node connections are held in another table:
create table brand_closure (
ancestor int unsigned not null,
descendant int unsigned not null,
primary key (ancestor,descendant),
foreign key fk_ancestor (ancestor) references brand(id),
foreign key fk_descendant (descendant) references brand(id)
);
This table will hold all connections on all levels between tree nodes:
insert into brand_closure values
(1,1),(1,2),(1,3),
(2,2),
(3,3),
(6,6),(6,7),(6,85),
(7,7),(7,85),
(85,85);
With this set up you can easily query the tree, for the expense of more work when modyfying the table. To get node and it's level:
select b.name, b.id, count(*) as level
from brand_closure a
join brand b on b.id = a.descendant
group by b.name;
+--------------+----+-------+
| name | id | level |
+--------------+----+-------+
| aston martin | 1 | 1 |
| bentley | 6 | 1 |
| continental | 7 | 2 |
| V8 | 3 | 2 |
| vanquish | 2 | 2 |
| 10 | 85 | 3 |
+--------------+----+-------+
Aston Martin
->Vanquish
->10
. 10 is just a name of child. When i select item with id 85 I need to know what index it is. Currently it is 3 as it has two parents. – Kin Mar 23 '16 at 12:00type
field which could be different. – Kin Mar 23 '16 at 12:01