Question

My mySql database contains some counting data tables of this type : date (DATETIME), data (INT).

I Would like create a view that addition data of 2 tables but I can't be sure that date of table1 are identic to date of table2.

For example :

Table1:

2013-01-01 10:00 / 100
2013-01-01 11:00 / 200
2013-01-01 12:00 / 300

Table2:

2013-01-01 11:00 / 500
2013-01-01 12:00 / 600
2013-01-01 13:00 / 700

With this 2 tables, I would like :
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

Thanks in advance for your help.

Était-ce utile?

La solution

How about this:

SELECT `date`, SUM(data) AS sum
  FROM (
     SELECT `date`, data FROM table1
     UNION ALL
     SELECT `date`, data FROM table2

  ) AS u
  GROUP BY `date`

If your table1 etc tables are very large you will probably get faster results by doing two things:

  1. creating a compound index (date, data) on each table.
  2. refactoring the query so each table is summarized before the UNION ALL.

The more efficient query might look like this.

  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 doesn't offer materialized views. That's Oracle.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top