首页 > 数据库 > mysql教程 > 如何高效地聚合 MySQL 中多个表的多个列的数据?

如何高效地聚合 MySQL 中多个表的多个列的数据?

Barbara Streisand
发布: 2025-01-21 11:01:09
原创
654 人浏览过

How Can I Efficiently Aggregate Data from Multiple Columns Across Multiple Tables in MySQL?

MySQL多表多列数据高效聚合方法

在丰富结果集的过程中,常常需要整合来自多个表格的数据,每个表格包含感兴趣的特定列。然而,使用多个SELECT语句来实现这一点可能会很繁琐且效率低下。

假设我们需要从两个表中检索汇总列,如下例所示:

<code class="language-sql">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>
登录后复制

这种方法通常会遇到问题,即只有第一列显示正确,而其他列的结果则错误。

解决方案是使用单个SELECT语句和条件聚合:

<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()函数聚合这些计数,生成所需的结果集。

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

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