Hierarchical queries in MySQL

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I m trying to find all the parents, grandparents, etc. of a particular field with any depth. For example, given the below structure, if I provide 5, the values returned should be 1, 2, 3 and 4.

| a  | b  |
-----------
| 1  | 2  |
| 2  | 3  |
| 3  | 4  |
| 4  | 5  |
| 3  | 6  |
| 4  | 7  |

How would I do this?

Answers

SELECT  @id :=
        (
        SELECT  senderid
        FROM    mytable
        WHERE   receiverid = @id
        ) AS person
FROM    (
        SELECT  @id := 5
        ) vars
STRAIGHT_JOIN
        mytable
WHERE   @id IS NOT NULL

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/8104187/hierarchical-queries-in-mysql

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils