gpt4 book ai didi

php - sql 查询 : how to make the parents without children?

转载 作者:行者123 更新时间:2023-11-29 02:05:27 25 4
gpt4 key购买 nike

我有这个查询来从这个 post 得到我想要的第一个结果早些时候,

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

但我现在有另一个问题,因为我想返回根本没有 child 的 parent ,

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 - 组函数的使用无效

我该如何解决?

最佳答案

只需在原始查询中添加一个 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 来过滤数据 before 聚合。 HAVING 用于在聚合 之后过滤结果。

关于php - sql 查询 : how to make the parents without children?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6944991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com