我的mySql数据库包含一些此类型的计数数据表:date(DATETIME),data(INT)。
我想创建一个视图,添加2个表的数据,但我不能确定table1的日期与table2的日期相同。
例如:
表1:
2013-01-01 10:00 / 100
2013-01-01 11:00 / 200
2013-01-01 12:00 / 300
表2:
2013-01-01 11:00 / 500
2013-01-01 12:00 / 600
2013-01-01 13:00 / 700
有了这两张桌子,我想:
View1 = Table1 + Table2
2013-01-01 10:00 / 100
2013-01-01 11:00 / 200 + 500 = 700
2013-01-01 12:00 / 300 + 600 = 900
2013-01-01 13:00 / 700
提前感谢您的帮助。
答案 0 :(得分:1)
这个怎么样:
SELECT `date`, SUM(data) AS sum
FROM (
SELECT `date`, data FROM table1
UNION ALL
SELECT `date`, data FROM table2
) AS u
GROUP BY `date`
如果你的table1
等表非常大,你可能会通过做两件事来获得更快的结果:
(date, data)
。UNION ALL
。效率更高的查询可能如下所示。
SELECT `date`, SUM(data) AS sum
FROM (
SELECT `date`, SUM(data) AS data FROM table1 GROUP BY `date`
UNION ALL
SELECT `date`, SUM(data) AS data FROM table2 GROUP BY `date`
UNION ALL
SELECT `date`, SUM(data) AS data FROM table3 GROUP BY `date`
UNION ALL
SELECT `date`, SUM(data) AS data FROM table4 GROUP BY `date`
) AS sums
GROUP BY `date`
MySQL不提供物化视图。这是甲骨文。