A
A
Anton Shelestov2017-02-24 14:35:57
MySQL
Anton Shelestov, 2017-02-24 14:35:57

How to get the number of child categories by an additional field?

Hello.
I can't figure out how to make a query to the database...
There is a table with columns id, parent_id, name
This is a table of categories, subcategories, subsubs, etc.
I want to get the top-level categories (parent_id = 0) and an additional field, for example, sub_count, which will contain the number of subcategories belonging to the parent.
Can this be done with one request?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene Khrustalev, 2017-02-24
@ShelestovAnt

select t.id, t.parent_id, t.name,
  (select count(*) from table tmp where t.id = tmp.parent_id) child_count
from table t
where t.parent_id is null or t.parent_id = 0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question