0

我有以下表结构,有很多这样的表:

data_1:
+-------+--------+-------+
| views | clicks | date  |
+-------+--------+-------+
|    29 |     1  | ..... |
|   458 |     9  | ..... |
+-------+--------+-------+ 
....

data_43:
+-------+--------+-------+
| views | clicks | date  |
+-------+--------+-------+
|     0 |     0  | ..... |
|     0 |     0  | ..... |
+-------+--------+-------+ 
...

我的问题是,如何在一个查询中获取所有总和值?

我尝试了一个简单的连接:

mysql> SELECT SUM(t1.views)  data_1_views,
              SUM(t1.clicks) data_1_clicks,
              SUM(t2.views)  data_43_views,
              SUM(t2.clicks) data_43_clicks
       FROM data_1 t1, data_43 t2;

但我的结果不是我所期望的:

+--------------+---------------+---------------+----------------+
| data_1_views | data_1_clicks | data_43_views | data_43_clicks |
+--------------+---------------+---------------+----------------+
|         NULL |          NULL |          NULL |           NULL |
+--------------+---------------+---------------+----------------+

我期望它是:

+--------------+---------------+---------------+----------------+
| data_1_views | data_1_clicks | data_43_views | data_43_clicks |
+--------------+---------------+---------------+----------------+
|         487  |          10   |             0 |              0 |
+--------------+---------------+---------------+----------------+

这里有人可以帮助我解决这个问题吗?
如果这比在多个查询中执行所有这些操作更高效,我也很感兴趣

4

2 回答 2

1

使用Union查询。

如下所示:

SELECT sum(t.data_1_views) as data_1_views,SUM(t.data_1_clicks) as data_1_clicks,
SUM(t.data_43_views) as data_43_views,SUM(t.data_43_views) as data_43_views
    FROM (
        SELECT SUM(t1.views)  data_1_views,SUM(t1.clicks) data_1_clicks,
        0 as data_43_views,0  as data_43_clicks
        FROM FROM data_1 as t1

        UNION

        SELECT 0 as data_1_views,0  as data_1_clicks,SUM(t1.clicks) as data_43_views, SUM(t2.clicks) 
        FROM data_43_clicks as t2 
       ) as t GROUP BY 1
于 2012-04-10T12:10:43.397 回答
1

在这种情况下,多个查询很好,特别是如果您对许多行进行分组。将这两个表集中在一个查询中几乎没有任何好处(实际上是潜在的错误)。我只会做两个查询

SELECT SUM(t1.views) data_1_views, SUM(t1.clicks) data_1_clicks
FROM data_1 t1 

SELECT SUM(t2.views) data_43_views, SUM(t2.clicks) data_43_clicks
FROM data_43 t2; 
于 2012-04-10T12:21:40.030 回答