我有这个标签表,
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
我想要返回这样的结果,
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
所以这是我到目前为止提出的查询,
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
但不幸的是,它只返回这样的结果,
ParentID ParentName TotalChildren
3 Tagname-1 2
5 tagname-2 2
6 tagname-3 1
9 tagname-4 1
这意味着没有孩子的父母会失踪。
如何让没有孩子的标签成为父母呢?或换句话说,如何让没有父母的标签自己成为父母?
修改
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
上面的答案返回,
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
这是错误的,因为它返回所有孩子。
答案 0 :(得分:1)
你快到了..只需要让连接成为外部连接:
已编辑:
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
答案 1 :(得分:0)
我在这里并不完全理解您的要求,但我会说,如果您将内部联接更改为左联接并将b.TotalChildren
更改为IF(b.TotalChildren is null, 0, b.TotalChildren)
,那么您将获得结果集欲望。
答案 2 :(得分:0)
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
答案 3 :(得分:0)
首选联接子查询:
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