我有这个查询来获取我之前想要的第一个结果{/ 3}},
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
返回,
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
但我现在有另一个问题,因为我想要归还没有孩子的父母,
ParentID ParentName TotalChildren
18 tagname-10 0
24 tagname-13 0
26 tagname-14 0
28 tagname-15 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
AND COUNT(childs.tag_id) = '0'
GROUP BY parents.tag_id, parents.tag_name
ORDER BY parents.tag_id
但它返回错误#1111 - Invalid use of group function
我该如何解决?
答案 0 :(得分:2)
只需在原始查询中添加HAVING
子句:
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
HAVING COUNT(childs.tag_id) = 0
ORDER BY parents.tag_id
您的问题是您尝试将WHERE
子句与聚合和函数(COUNT
)一起使用。但是,您应该使用WHERE
在聚合之前过滤数据。 HAVING
用于在聚合后过滤结果。
答案 1 :(得分:1)
更改此部分
AND COUNT(childs.tag_id) = '0'
GROUP BY parents.tag_id, parents.tag_name
到
GROUP BY parents.tag_id, parents.tag_name
HAVING COUNT(childs.tag_id) = 0
答案 2 :(得分:0)