我之前使用过此查询
SELECT
categories.*, projects.pid, projects.name, parent_category.*
FROM categories
INNER JOIN projects ON projects.pid = categories.project
LEFT JOIN categories AS parent_category ON parent_category.pid = categories.parent
效果很好
这次,我们需要SUM,COUNT个数据。所以我添加了“ counts”表并进行了查询。
SELECT
categories.*, projects.pid, projects.name, SUM(counts.count), COUNT(counts.count),
parent_category.*, SUM(parent_category_count.count), COUNT(parent_category_count.count)
FROM categories
INNER JOIN projects ON projects.pid = categories.project
LEFT JOIN counts ON counts.category = categories.pid
LEFT JOIN categories AS parent_category ON parent_category.pid = categories.parent
LEFT JOIN counts AS parent_category_count ON parent_category_count.category = categories.pid
然后我得到
错误:聚合函数调用无法嵌套
我该怎么办?这个查询基本上有意义吗?还是应该拆分?
答案 0 :(得分:1)
您应该添加适当的GROUP BY子句(在您的情况下应为Categories.pid)
SELECT
categories.*
, projects.pid
, projects.name
, SUM(counts.count)
, COUNT(counts.count)
, parent_category.*
, SUM(parent_category_count.count)
, COUNT(parent_category_count.count)
FROM categories
INNER JOIN projects ON projects.pid = categories.project
LEFT JOIN counts ON counts.category = categories.pid
LEFT JOIN categories AS parent_category ON parent_category.pid = categories.parent
LEFT JOIN counts AS parent_category_count ON parent_category_count.category = categories.pid
GROUP BY categories.pid
或根据您的评论
SELECT
categories.*
, projects.pid
, projects.name
, SUM(counts.count)
, COUNT(counts.count)
, parent_category.*
, SUM(parent_category_count.count)
, COUNT(parent_category_count.count)
FROM categories
INNER JOIN projects ON projects.pid = categories.project
LEFT JOIN counts ON counts.category = categories.pid
LEFT JOIN categories AS parent_category ON parent_category.pid = categories.parent
LEFT JOIN counts AS parent_category_count ON parent_category_count.category = categories.pid
GROUP BY categories.pid, projects.pid, parent_category.pid