I have table 'pe' with columns id, name, and lcltyid I have table 'wp_exrz_locality_localities' with id, name, and parent
the locality table is a tree and the parent contains an id of another locality row. pe.lcltyid is a key wp_exrz_locality_localities.id
basically what I want to do is retrieve all 'pe' entries sorted by their "tree depth"
However the total depth of the tree can be any amount at any time. And I need the depth in a way that allows me to use it in a sub query for sorting.
Originally I thought I needed a stored proceedure/function to get the depth of a lclty entry. After i made the proceedure I found out that proceedures cant be used in expressions. Then I tried to make a function but binary logging is enabled by me host and "log_bin_trust_function_creators = 0", so no stored functions for me.
Lastly I am trying to understand recursion but can 't seem to make it work. I am just trying to create a recursive statement that will retrieve the "depth" meaning the number of parents for an individual node up until the top node, or when the parent = 0 I just get an error "syntax to use near 'RECURSIVE node_ancestors..."
WITH RECURSIVE node_ancestors(id, parent) AS (
SELECT id, id FROM `wp_exrz_locality_localities` WHERE id IN (1, 2, 3)
UNION ALL
SELECT na.id, wp_exrz_locality_localities.parent
FROM node_ancestors AS na, wp_exrz_locality_localities
WHERE wp_exrz_locality_localities.id = na.parent AND wp_exrz_locality_localities.parent != 0
)
SELECT id, COUNT(parent) AS depth FROM node_ancestors GROUP BY id;
Any help is greatly appreciated
an example: EDIT table pe:
id---name---lcltyid
2---first---4
3---second---3
table wp_exrz_locality_localities:
id---name---parent
1---USA---0
3---SanFran---1
4---California---3
SELECT * FROM 'pe' ORDER BY ([lcltydepth]) ASC;
desired output:
id---name---lcltyid
3---second---3
2---first---4
where lclctydepth is 3 for the "first" pe and 2 for "second" because the second one is attached to a state with only the US above it and the first one is attached to a city, with state and US above it. So it would order them by the number of parents required to get the the last parent with parentid = 0;
I hope this helps?