【问题标题】:Join two count query is not giving right result加入两个计数查询没有给出正确的结果
【发布时间】:2021-04-12 07:29:26
【问题描述】:

我试图加入两个查询来比较计数

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 

我没有得到与单独运行它们相同的结果,我做错了什么

【问题讨论】:

  • 此处不适合加入。我建议大家联合

标签: mysql join group-by count union-all


【解决方案1】:

根据您的要求,您需要 2 个查询中的一个 FULL OUTER JOIN,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

【讨论】:

  • 如果可能的话,请您解释一下查询语法,t 是别名吗?帖子计数后为 0 用于@forpas?
  • MySql 中的所有子查询/派生表都必须有别名。 t 是主查询的 FROM 子句之后的子查询的别名。
猜你喜欢
  • 2023-03-14
  • 2019-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-10
相关资源
最近更新 更多