Friday, 21 April 2017

SQL all rows in child 'categories' and child child 'categories' : recursive?

I'm having trouble writing a query that solves the following problem, which I believe needs some kind of recursiveness:

I have a table with houses, each of them having a specific house_type, p.e. house, bungalow, etc. The house_types inherit from each other, also declared in a table called house_types.

table: houses
id | house_type
1  | house
2  | bungalow
3  | villa
etcetera...

table: house_types
house_type | parent
house      | null
villa      | house
bungalow   | villa
etcetera...

In this logic, a bungalow is also a villa and a villa is also house. So when I want to get all villas, house 2 and 3 should show up, when I want to get all houses, house 1, 2 and 3 should show up, when I want all bungalows, only house 3 should show up.

Is a recursive query the answer and how should I work this out. I use knex/objection.js in a node.js application.



via Mats de Swart

No comments:

Post a Comment