SQL查询:如何以最有效的方式合并合并查询

时间:2014-05-21 19:06:53

标签: mysql sql

我有很多表,我想从每个表中隔离数据并计算总数。

SELECT country, SUM(count) AS count from (
    SELECT country, SUM(count) AS count from table_1 GROUP BY country
    union all
    SELECT country, SUM(count) AS count from table_2 GROUP BY country
    union all
    ............
    union all
    SELECT country, SUM(count) AS count from table_n GROUP BY country)
A GROUP BY country;

此查询的问题是在最终计算之前从table_1 ... table_n获取结果。这会使尺寸变大并占用大量内存。

是否有解决方案可以改善它。

这样的东西
SELECT country, SUM(count) AS count from (
    SELECT country, SUM(count) AS count from table_1 GROUP BY country
    union all
    SELECT country, SUM(count) AS count from table_2 GROUP BY country) 
A GROUP BY country;

then 

SELECT country, SUM(count) (
A 
    union all (SELECT country, SUM(count) AS count from table_3 GROUP BY country)
) A GROUP BY country;

......

until table_n
?

有人请建议任何更好的解决方案吗?

1 个答案:

答案 0 :(得分:0)

您可以嵌套联盟:

SELECT country, SUM(count) AS count
FROM (SELECT country, SUM(COUNT) AS count
      FROM table_1
      GROUP BY country
      UNION ALL
      SELECT COUNTRY, SUM(count) AS count
      FROM 
          (SELECT country, SUM(count) AS count
           FROM table_2
           GROUP BY country
           UNION ALL
           SELECT country, SUM(count) AS count
           FROM
               (SELECT country, SUM(count) AS count
                FROM table_3
                GROUP BY country
                UNION ALL
                SELECT country, SUM(count) AS count
                FROM table_4
                GROUP BY country)
           GROUP BY country)
      GROUP BY country)
GROUP BY country

根据需要为所有表格保持多次嵌套。

另一种方法是将中间联合保存到临时表中。