I have a MySQL table articles
in which I have organized the content in the following hierarchy:
- Section
- Subject
- Chapter
- Post
Each item from the above is on a row having fields: id
, parent
, name
etc.
The post row parent
equals chapter row id
, chapter row parent
equals subject row id
and subject row parent
equals section row id
.
I don't have taller hierarchy than above.
I need to select the list of subjects in the a given section along with the count of all children of each subject. The count is the sum of number of descendant chapters and their descendants which are posts.
My brother helped me with the following select query. However it is relatively slow at ~0.6 seconds.
SELECT
subjects.id,
subjects.name,
subjects.link,
(
SELECT
COUNT(DISTINCT posts.id)
FROM
articles AS chapters,
articles AS posts
WHERE
chapters.parent = subjects.id AND(
posts.parent = chapters.id OR posts.parent = subjects.id
)
) AS child_count
FROM
articles AS subjects
WHERE
subjects.parent = 62
I need help with improving the performance please.
Thanks a lot!!