L
L
Lander2015-06-18 16:24:30
JavaScript
Lander, 2015-06-18 16:24:30

How to write a query on a table with an internal relationship?

It seems to me that the question is elementary, but what I dug up on the Internet is not about that at all. The bottom line is this:
There is a table:

id;name;parent
1;alex;0
2;mary;1
3;alice;1
4;hoover;2

the parent field is a link to the parent's id.
Is it possible somehow to get the entire chain of elements for a given id with one request? For example for id = 4 get:
id;name;parent
4;hoover;2
2;mary;1
1;alex;0

Thanks in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Shamanov, 2018-09-13
@SilenceOfWinter

on('submit', must not required fields are not filled
as an option to bypass all elements with required loop and check .var()

A
Alexey Ukolov, 2015-06-18
@usdglander

If nesting is limited, then joins can be used (according to the number of nesting levels). But even in this case, as in your question, it will not work - everything will be one line.
If nesting is unlimited, then no way.

I
icetomcat, 2015-06-18
@kostia256

id;name;parent
1;alex;0
2;mary;1
3;alice;1
4;hoover;2

Convert to 2 tables of the form:
id;name
1;alex
2;mary
3;alice
4;hoover

parent_id;element_id
1;2
1;3
1;4
2;4

List of all parents for element 4:
List of all children for element 1:
For convenience, you can add the level and position fields to the `people` table, and get children or parents for any number of nesting levels. And position is for positioning elements at each level for each parent.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question