gpt4 book ai didi

MySQL 查询返回错误的 COUNT 值

转载 作者:行者123 更新时间:2023-11-29 06:49:33 26 4
gpt4 key购买 nike

在这里我分享了我的疑问。所有总计值都会给出错误的结果,因为非常大的数值不是所需的 COUNT 值。我的查询有什么问题?

           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

最佳答案

由于您的问题中没有示例数据集,我的猜测是您多次获得相同的 manager_id、agent_id...,因为左连接使用不同的值来获取正确的计数

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

还包括分组依据中的所有非聚合列,因为根据新版本,大多数 RDBMS 拒绝这些类型的查询

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

关于MySQL 查询返回错误的 COUNT 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48052077/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com