SELECT id,title,subtitle,label,( SELECT COUNT(*) FROM content_info WHERE theme_id=topic.id AND is_delete=1 GROUP BY id) AS contentNum,( SELECT COUNT(*) FROM content_info WHERE theme_id=topic.id AND is_delete=1 GROUP BY union_id) AS peopleNum FROM topic contentNum和peopleNum 为什么等于null
时间: 2024-03-25 19:40:16 浏览: 107
在这个查询语句中,contentNum 和 peopleNum 的值可能会为 NULL 是因为子查询中使用了 GROUP BY 子句,而没有对 id 和 union_id 进行聚合操作。这样会导致子查询返回多个值,而 SELECT 子句只能接受一个值,因此会抛出一个错误。解决方法有两种:
1. 在子查询中去掉 GROUP BY 子句,改用 COUNT(*) 统计总数。
```
SELECT id, title, subtitle, label,
(SELECT COUNT(*) FROM content_info WHERE theme_id = topic.id AND is_delete = 1) AS contentNum,
(SELECT COUNT(DISTINCT union_id) FROM content_info WHERE theme_id = topic.id AND is_delete = 1) AS peopleNum
FROM topic;
```
2. 在子查询中使用 GROUP BY 子句,并将聚合函数的结果命名为一个别名,然后在外层查询中使用 MAX 或者 SUM 函数来获取别名对应的值。
```
SELECT id, title, subtitle, label,
MAX(contentNum) AS contentNum,
MAX(peopleNum) AS peopleNum
FROM (
SELECT topic.id, topic.title, topic.subtitle, topic.label,
COUNT(*) AS contentNum,
COUNT(DISTINCT union_id) AS peopleNum
FROM topic
LEFT JOIN content_info ON topic.id = content_info.theme_id
WHERE content_info.is_delete = 1
GROUP BY topic.id
) t;
```
这个查询中,使用了一个子查询来计算 contentNum 和 peopleNum 的值,并将结果命名为别名。然后在外层查询中使用 MAX 函数来获取别名对应的值,这样就可以避免由于子查询返回多个值而导致的 NULL 值问题。
阅读全文