派生表使用group by

时间:2014-10-02 04:50:26

标签: mysql group-by

我试图合并来自2个不同表的结果,其中两个表具有完全相同的模式和字段,如下所示:

select * from 
(select query_type, count(query_type), campaign_id from table1 
UNION ALL
select query_type, count(query_type), campaign_id from table2
) derivedTable  group by query_type,campaign_id;

但是,我没有收到包含所有query_type和campaign_id的结果。 有人可以告诉我错过了什么吗?

2 个答案:

答案 0 :(得分:1)

聚合函数必须位于GROUP BY所在的同一查询(或子查询)中,所以:

select query_type, count(query_type), campaign_id
from (
    select query_type, campaign_id from table1
    UNION ALL
    select query_type, campaign_id from table2
  ) derivedTable
group by query_type,campaign_id;

因为您的子查询使用聚合函数但没有GROUP BY,所以此子查询只返回一行:

select query_type, count(query_type), campaign_id from table1

答案 1 :(得分:1)

试试这个

SELECT
      query_type
    , campaign_id
    , COUNT(query_type)
FROM (
            SELECT
                  query_type
                , campaign_id
            FROM table1
            UNION ALL
                  SELECT
                        query_type
                      , campaign_id
                  FROM table2
      ) derivedTable
GROUP BY
      query_type
    , campaign_id
;

或者这个:

SELECT
        query_type
      , campaign_id
      , SUM(query_type)
FROM (
            SELECT
                  query_type
                , COUNT(query_type)
                , campaign_id
            FROM table1
            GROUP BY
                  query_type
                , campaign_id
            UNION ALL
                  SELECT
                        query_type
                      , COUNT(query_type)
                      , campaign_id
                  FROM table2
                  GROUP BY
                        query_type
                      , campaign_id
      ) derivedTable
GROUP BY
      query_type
    , campaign_id
;

如果第二个表是远程的,第二个表格可能很有用,否则上面的第一个表格最简单。