MySQL multi-table and multi-column data efficient aggregation method
In the process of enriching a result set, it is often necessary to integrate data from multiple tables, each table containing a specific column of interest. However, using multiple SELECT statements to achieve this can be tedious and inefficient.
Suppose we need to retrieve summary columns from two tables as shown in the following example:
<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>
This approach often suffers from the problem that only the first column is displayed correctly, while the results for the other columns are wrong.
The solution is to use a single SELECT statement and conditional aggregation:
<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>
In this modified statement, the conditional aggregation uses the IF() function to evaluate the specific PAT_STATUS pattern in each row, incrementing the count of matching patterns. The SUM() function then aggregates these counts to produce the desired result set.
The above is the detailed content of How Can I Efficiently Aggregate Data from Multiple Columns Across Multiple Tables in MySQL?. For more information, please follow other related articles on the PHP Chinese website!