mysql查询返回错误的计数值

cgh8pdjw  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(346)

这里我分享了我的疑问。所有的总值都给出了错误的结果,因为它们是非常大的数值,而不是期望的计数值。我的问题是什么?

SELECT bd.business_id,
                  bd.business_name,
                  bd.business_address,
                  bd.created_at,
                  bd.updated_at AS extent_expiry_date,
                  bd.manager_id as user_id,
                  COUNT(m.manager_id) AS total_managers,
                  COUNT(a.agent_id) AS total_agents,
                  COUNT(c.customer_id) AS total_customers,
                  COUNT(t.task_id) AS total_tasks,
                  COUNT(t.order_id) AS total_orders
            FROM business_details bd
            LEFT JOIN managers m ON m.business_id = bd.business_id
            LEFT JOIN agents a ON a.business_id = bd.business_id
            LEFT JOIN customers c ON c.business_id = bd.business_id
            LEFT JOIN tasks t ON t.business_id = bd.business_id
            GROUP BY bd.business_id
7lrncoxx

7lrncoxx1#

由于您的问题中没有样本数据集,我猜您得到的是相同的经理id、代理id。。。多次由于左连接得到正确的计数使用distinct

SELECT bd.business_id,
      bd.business_name,
      bd.business_address,
      bd.created_at,
      bd.updated_at AS extent_expiry_date,
      bd.manager_id as user_id,
      COUNT(distinct m.manager_id) AS total_managers,
      COUNT(distinct a.agent_id) AS total_agents,
      COUNT(distinct c.customer_id) AS total_customers,
      COUNT(distinct t.task_id) AS total_tasks,
      COUNT(distinct t.order_id) AS total_orders
FROM business_details bd
LEFT JOIN managers m ON m.business_id = bd.business_id
LEFT JOIN agents a ON a.business_id = bd.business_id
LEFT JOIN customers c ON c.business_id = bd.business_id
LEFT JOIN tasks t ON t.business_id = bd.business_id
GROUP BY bd.business_id

根据新版本,还可以将所有未聚合的列包含在group by中,因为大多数rdbms都拒绝这些类型的查询

GROUP BY 
bd.business_id,
bd.business_name,
bd.business_address,
bd.created_at,
bd.updated_at,
bd.manager_id

相关问题