onsulta @ sql: como fazer as tags sem filhos para se tornarem pais?
Tenho esta tabela de tags,
tag_id tag_name parent_id cat_id
3 Tagname-1 NULL NULL
5 tagname-2 NULL NULL
6 tagname-3 NULL NULL
9 tagname-4 NULL NULL
11 tagname-5 3 NULL
13 tagname-6 3 NULL
15 tagname-8 5 NULL
17 tagname-9 5 NULL
18 tagname-10 NULL NULL
20 tagname-11 6 NULL
22 tagname-12 9 NULL
24 tagname-13 NULL NULL
26 tagname-14 NULL NULL
28 tagname-15 NULL NULL
Quero retornar um resultado como esse,
ParentID ParentName TotalChildren
3 Tagname-1 2
5 tagname-2 2
6 tagname-3 1
9 tagname-4 1
18 tagname-10 0
24 tagname-13 0
26 tagname-14 0
28 tagname-15 0
Então aqui a consulta que eu saí até agora,
SELECT
a.tag_id as ParentID,
a.tag_name as ParentName,
b.TotalChildren
FROM root_tags a INNER JOIN
(
SELECT parent_id, COUNT(1) as TotalChildren
FROM root_tags
WHERE parent_id <> tag_id
GROUP BY parent_id
) b
ON a.tag_id = b.parent_id
ORDER BY ParentID
Mas, infelizmente, ele apenas retorna o resultado assim,
ParentID ParentName TotalChildren
3 Tagname-1 2
5 tagname-2 2
6 tagname-3 1
9 tagname-4 1
O que significa que faltam os pais sem filhos.
Como posso fazer as tags sem filhos para se tornarem pais também? ou, em outras palavras, como fazer as tags sem que os pais se tornem pais?
EDITAR
SELECT
a.tag_id as ParentID,
a.tag_name as ParentName,
b.TotalChildren
FROM root_tags a LEFT OUTER JOIN
(
SELECT parent_id, COUNT(1) as TotalChildren
FROM root_tags
WHERE parent_id <> tag_id
GROUP BY parent_id
) b
ON a.tag_id = b.parent_id
ORDER BY ParentID
a resposta acima retorna,
ParentID ParentName TotalChildren
3 Tagname-1 2
5 tagname-2 2
6 tagname-3 1
9 tagname-4 1
11 tagname-5 NULL
13 tagname-6 NULL
15 tagname-8 NULL
17 tagname-9 NULL
18 tagname-10 NULL
20 tagname-11 NULL
22 tagname-12 NULL
24 tagname-13 NULL
26 tagname-14 NULL
28 tagname-15 NULL
que está incorreto, pois retorna todos os filho