mysql - 加入两个计数查询没有给出正确的结果
问题描述
我试图加入两个查询来比较计数
SELECT count(customer_id) , customer_id
FROM `blog_post`
group by customer_id
第二个查询是
SELECT count(customer_id)
FROM `blog_comment`
WHERE `is_admin` IS NOT NULL
group by customer_id
我创建的连接查询是
SELECT count(post.customer_id) as post_count , post.customer_id ,
count(comment.customer_id)
FROM `blog_post` as post
left join blog_comment as comment on post.customer_id = comment.customer_id
WHERE `is_admin` IS NOT NULL
GROUP BY post.customer_id
我没有得到与单独运行它们相同的结果,我做错了什么
解决方案
根据您的要求,您需要FULL OUTER JOIN
2 个查询中的一个,MySql 不支持该查询,只能使用LEFT/RIGHT
连接和UNION ALL
.
做你想做的另一种方法是使用UNION ALL
2 个查询并汇总结果:
SELECT customer_id,
MAX(post_count) post_count,
MAX(comment_count) comment_count
FROM (
SELECT customer_id, COUNT(*) post_count, 0 comment_count
FROM `blog_post`
GROUP BY customer_id
UNION ALL
SELECT customer_id, 0, COUNT(*)
FROM `blog_comment`
WHERE `is_admin` IS NOT NULL
GROUP BY customer_id
) t
GROUP BY customer_id
推荐阅读
- angular - Angular 2+:获取@ViewChild() 的子元素
- javascript - onkeyup 激活许多 ajax 请求
- python - Python:获取亚马逊 s3 存储桶中的前 100 个最新密钥
- vba - 允许用户选择 csv 的 VBA 不起作用
- circuit - 如何为机器人实现 OAuth 2 Circuit REST API?
- ios - 将 .html 从 iOS 应用资源加载到 WebView 中?
- llvm - 在 llvm 的 PassManager 中添加 TargetData 时出错
- reactjs - 将数组放入新组件时,对象不是函数错误
- docker - Sonarr/Radarr Remote path mapping to docker transmission
- sql-server - TSQL-使用函数调用动态查询时出错