This is a follow up from my question: “MySQL: Querying a table and possibly replacing some fields with values from another table”
I have two tables. Table1 is our main table of data and Table2 has a subset of the Table1 columns and a subset of the records contained in Table1. You can see Table2 as a table holding corrected values for some of Table1’s records.
Here are my tables with sample data:
Table1
| page_id | field_id | date | value | bla |
--------------------------------------------------|
| 1 | 1 | 2012-01-01 | 3 | 1 |
| 2 | 1 | 2012-01-01 | 10 | 2 |
| 3 | 1 | 2012-01-01 | 25 | 2 |
| 1 | 2 | 2012-01-01 | 11 | 3 |
| 2 | 2 | 2012-01-01 | 22 | 1 |
| 3 | 2 | 2012-01-01 | 33 | 2 |
Table2
| page_id | field_id | date | value |
-------------------------------------------
| 1 | 1 | 2012-01-01 | 1 |
| 2 | 1 | 2012-01-01 | 2 |
| 3 | 1 | 2012-01-01 | 3 |
| 4 | 1 | 2012-01-01 | 4 |
I want to calculate the sum of values for one or more field_ids, following these rules:
(1) If records for one of the specified field_id exists only in Table1, I want to sum both value and bla for all records where field_id match the specified field_id
(2) If the field_id exists in both Table1 and Table2, then we would get the sum of value from Table2 and the sum of bla from Table1.
Here is the query I am using:
SELECT t1.field_id,
SUM(IFNULL(t2.value, IFNULL(t1.value,0))) as 'Value Sum',
SUM(IFNULL(t1.bla,0)) as 'Bla Sum'
FROM test.Table1 t1
LEFT JOIN test.Table2 t2 ON t1.field_id = t2.field_id
WHERE (t1.field_id IN (1,2))
GROUP BY t1.field_id, t1.date;
But I am not getting the correct sums for field_1:
|field_id | Value Sum | Bla Sum|
---------------------------------
| 1 | 30 | 20 | <-- was expecting 10 and 5, respectively
| 2 | 66 | 6 |
Would you have any idea what I could be doing wrong?
Thanks in advance!
You need to add also the page_id to the JOIN otherwise the 3 row from table1 and 4 of table2 for field_id1 result in 12 columns
also removed the group by
t1.date