Saturday, 24 August 2013

Best way to select hierchial data from different SQL tables

Best way to select hierchial data from different SQL tables

I'm using SQL Server 2012. I have a hierarchical structure of tables for
categories, pages, and sections.
Each category has zero or more pages and each page has zero or more
sections. I would like to display all categories that match a certain
query as well as all of their respective pages, in line with them, and
then all of those pages' respective sections.
For example:
Category 1:
Page A
Page B
Category 2
Page C (section 1, section 2, section 3)
As far as I can tell this requires one query for the categories then while
iterated through the categories, I need to make 2 page query (eg. SELECT *
FROM pages P WHERE P.category = 1). Finally, for each page I need to make
a section query (3 in total). This means I have to make 6 queries just to
get the data above. Is there a better way?

No comments:

Post a Comment