首页 > 数据库 > mysql教程 > 如何在SQL中高效查询不同表的多列?

如何在SQL中高效查询不同表的多列?

DDD
发布: 2025-01-21 10:51:10
原创
505 人浏览过

How to Efficiently Query Multiple Columns from Different Tables in SQL?

优化多表多列SQL查询

从多个表中检索数据通常会带来挑战,特别是在需要聚合各个列中的值时。最近的一个支持案例强调了用户在准确计算两个表中多个列的值时遇到的困难。他们最初尝试使用嵌套子查询,但产生了错误的结果。

有缺陷的查询如下所示:

<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>
登录后复制

解决方案在于在单个查询中使用条件聚合。这种简化的方法根据指定条件计算多个列,提供准确的结果。 改进后的查询是:

<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>
登录后复制

此修改后的查询可有效检索必要的数据,消除与原始过于复杂的结构相关的错误。 关键是使用条件 SUM() 语句将计算合并为一个结构良好的查询。

以上是如何在SQL中高效查询不同表的多列?的详细内容。更多信息请关注PHP中文网其他相关文章!

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