2

我有这个查询是为了从之前的这篇文章中得到我想要的第一个结果,

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

我该如何解决?

4

3 回答 3

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

于 2011-08-04T16:26:31.073 回答
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
于 2011-08-04T16:27:00.977 回答
0

使用 HAVING 而不是 WHERE,并且在 GROUP BY 之后

http://blog.cnizz.com/tag/mysql-error-1111/

这可能很有用。

于 2011-08-04T16:35:30.910 回答