首页 > 数据库 > mysql教程 > 如何有效聚合同一个 MySQL 表中不同列的多个计数?

如何有效聚合同一个 MySQL 表中不同列的多个计数?

Linda Hamilton
发布: 2025-01-21 11:06:09
原创
966 人浏览过

How to Efficiently Aggregate Multiple Counts from Different Columns in the Same MySQL Table?

MySQL:有效聚合单个表中多个列的计数

针对 MySQL 中同一个表但不同列的多个查询可能会导致数据检索效率低下和结果不准确。 让我们用一个例子来说明这一点并展示正确的方法。

假设您需要根据t_hospital表中的各种条件计算计数:

低效方法(多次查询):

以下代码尝试使用多个查询来实现此目的,但它会为第一个查询之外的列生成错误的结果:

<code class="language-sql">SET @start_res = 20150301;
SET @finish_res= 20150501;
SET @finish_check= 20150801;
SET @start_check= 20150301;
SET @daily_hos= 3;

SELECT* from
   ( SELECT COUNT(DAY_IN) AS arr FROM t_hospital WHERE DAY_IN between  @start_check and @finish_check and RES_DATE between @start_res and @finish_res  and ID_daily_hos =@daily_hos group by DAY_IN  )e,
     (SELECT COUNT(PAT_STATUS) AS ONG1 FROM t_hospital WHERE PAT_STATUS  like '%ong%' and  DAY_IN between @start_check and @finish_check and RES_DATE between @start_res and @finish_res  and ID_daily_hos =@daily_hos group by DAY_IN ) a,
        (SELECT COUNT(PAT_STATUS) AS RTED FROM t_hospital WHERE PAT_STATUS  like '%rtde%'and  DAY_IN between  @start_check and @finish_check and RES_DATE between @start_res and @finish_res  and ID_daily_hos =@daily_hos group by DAY_IN  )b,
           (SELECT COUNT(PAT_STATUS) AS POLI FROM t_hospital WHERE PAT_STATUS  like '%pol%'and DAY_IN between @start_check and @finish_check and RES_DATE between @start_res and @finish_res  and ID_daily_hos =@daily_hos group by DAY_IN   )c,
              (SELECT COUNT(PAT_STATUS) AS para FROM t_hospital WHERE PAT_STATUS  like '%para%' and  DAY_IN between @start_check and @finish_check and RES_DATE between @start_res and @finish_res  and ID_daily_hos =@daily_hos group by DAY_IN  )d;</code>
登录后复制

高效方法(带条件聚合的单查询):

最佳解决方案涉及使用条件聚合的单个查询:

<code class="language-sql">SELECT DAY_IN, COUNT(*) AS arr,
        SUM(IF(PAT_STATUS  like '%ong%', 1, 0)) AS ONG1,
        SUM(IF(PAT_STATUS  like '%rtde%', 1, 0)) AS RTED,
        SUM(IF(PAT_STATUS  like '%pol%', 1, 0)) AS POL1,
        SUM(IF(PAT_STATUS  like '%para%', 1, 0)) AS para
FROM t_hospital 
WHERE DAY_IN between @start_check and @finish_check 
    and RES_DATE between @start_res and @finish_res  
    and ID_daily_hos =@daily_hos
GROUP BY DAY_IN;</code>
登录后复制

此方法利用 IF() 函数根据 PAT_STATUS 值有条件地计算出现次数,并且 SUM() 聚合每个 DAY_IN 的这些计数。该方法显着提高了效率并提供了准确的结果。 它避免了通过连接多个子查询隐式创建的笛卡尔积。

以上是如何有效聚合同一个 MySQL 表中不同列的多个计数?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板