加入两个计数查询没有给出正确的结果
Join two count query is not giving right result
我试图加入两个查询来比较计数
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
我得到的结果与 运行 他们单独得到的结果不同,我做错了什么
根据您的要求,您需要 2 个查询中的 FULL OUTER JOIN
个,MySql 不支持,只能用 LEFT/RIGHT
连接和 UNION ALL
模拟。
另一种方法是对 2 个查询使用 UNION ALL
并汇总结果:
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
我试图加入两个查询来比较计数
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
我得到的结果与 运行 他们单独得到的结果不同,我做错了什么
根据您的要求,您需要 2 个查询中的 FULL OUTER JOIN
个,MySql 不支持,只能用 LEFT/RIGHT
连接和 UNION ALL
模拟。
另一种方法是对 2 个查询使用 UNION ALL
并汇总结果:
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