This might be what you are looking for, according to your description:
the most-specific (
LENGTH()
-iest prefix) rate, but not being limited to${user rate plan ID}
, but instead picking rates from those affiliated
WITH RECURSIVE cte AS (
SELECT id, parent_rate_plan_id
FROM rate_plan
WHERE id = ${user rate plan ID}
UNION ALL
SELECT rp.id, rp.parent_rate_plan_id
FROM cte
JOIN rate_plan rp ON rp.id = cte.parent_rate_plan_id
)
SELECT *
FROM cte
JOIN rate r ON r.rate_plan_id = cte.id
ODER BY length(prefix) DESC
LIMIT 1;
Recursion stops automatically as soon as the top node (parent_rate_plan_id IS NULL
) is reached.
It's more effective to join to rate
once after you have collected all plans.