sql query: how to make the tags without children to become parents?

这一生的挚爱 提交于 2019-12-02 09:11:55

Prefer a Join against a Subquery:

SELECT parents.tag_id AS ParentID,
       parents.tag_name AS ParentName,
       COUNT(childs.tag_id) AS TotalChildren
FROM root_tags AS parents
    LEFT OUTER JOIN root_tags AS childs
        ON parents.tag_id = childs.parent_id
WHERE parents.parent_id IS NULL
GROUP BY parents.tag_id, parents.tag_name
ORDER BY parents.tag_id

You're nearly there.. just need to make the join an outer one:

EDITED:

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
WHERE b.TotalChildren is not null
ORDER BY ParentID

I don't completely understand your requirement here, but I'll say that if you change the inner join to a left join and b.TotalChildren to IF(b.TotalChildren is null, 0, b.TotalChildren) then you'll get the result set you desire.

SELECT 
a.tag_id as ParentID,
a.tag_name as ParentName,
count(b.child) as TotalChildren
FROM root_tags as a INNER JOIN
(
  SELECT parent_id as child FROM root_tags
  WHERE parent_id is not NULL
)  as b
ON a.tag_id = b.child
where a.parent_id is NULL
ORDER BY ParentID
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!