For simplicity and clarity, I have the following two SQL table structures:
tbl1: col1, col2, col3
tbl2: col1, col2, col3
Both tables have the same number of columns, and the column IDs in both tables are the same. Also, for both tables, all values in col1 are the same. Both tables have approximately 2000 entries, all of which are integers, and both tables typically have the same number of entries.
Now, I have a third table that has the same structure as the first two, that I am trying to populate with the sums of every value in each column from the first two tables as follows:
tbl3: col1, (tbl1.col2+tbl2.col2), (tbl1.col3+tbl2.col3)
Eventually, I will also have a fourth table that will have the average of every value in the first two tables as follows:
tbl3: col1, (tbl1.col2+tbl2.col2)/2, (tbl1.col3+tbl2.col3)/2
I have been researching how to do this using subqueries and union operations such as those described by @Jonysuise here but when I do this I am seeing incorrect values inserted into tbl3, no values at all, or PDO syntax errors.
Also, I am executing this via PDO due to how this data needs to be handled upstream, and as I am less familiar with this structure I have started wondering if there exists some different recommended way of doing this that I am just not getting.
The last version of this that did not throw errors was:
$db->exec("INSERT INTO tbl3 (col1, col2, col3) select col1, sum(col2), sum(col3) as total
from
(
select col1,col2,col3
from tbl1
union all
select col1,col2,col3
from tbl2
) t
group by col1");
I am trying to find a more efficient way to do this especially one that can accommodate other mathematical operations such as averages.
EDIT: Just to clarify, when I run the script above, if there are no errors, I typically get a value in tb3 that is greater than expected.