G
G
G0rDi2011-03-04 14:59:19
MySQL
G0rDi, 2011-03-04 14:59:19

Counting children of a node in MySQL?

Good afternoon.
There is a table:

CREATE TABLE sections (<br/>
 id_sections INT(11) NOT NULL AUTO_INCREMENT,<br/>
 name VARCHAR(255) DEFAULT NULL,<br/>
 parent INT(11) UNSIGNED NOT NULL,<br/>
 PRIMARY KEY (id_sections)<br/>
)<br/>

In which a two-level tree is stored in the parent field, the id_sections of the parent is stored.
It is required to create a query to display all root directories (parent = 0) with the number of subdirectories.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
shsmad, 2011-03-04
@shsmad

SELECT s1.*, count(s2.id_sections)
FROM sections s1
LEFT JOIN sections s2 ON s2.parent = s1.id_sections
WHERE s1.parent = 0
GROUP BY s1.id_sections

not?

D
drVano, 2011-03-04
@drVano

Isn't MySQL able to do this?
SELECT *, (SELECT COUNT(*) FROM sections s2 WHERE s2.parent = s1.id_sections)
FROM sections s1
WHERE s1.parent = 0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question