SELECT SUM(t.P01) AS total_P01, SUM(t.P02) AS total_P02
FROM (SELECT P01, P02 FROM graduate_survey
UNION ALL
SELECT P01, P02 FROM Alumni_survey) t
This works. Based on: How can I sum columns across multiple tables in MySQL?
I'm not marking it as duplicate because the resource is for one value, here are two.
Adding results of type DECIMAL(10,6) from 2 real tables with 18k+57k entries the query takes about 0.15s to complete.
Part 2: INSERT
Assuming your new table has AUTO INCREMENT on T_id (pk) and you have fetched the previous result with mysql_fetch_assoc()
into $row:
$query_string = "INSERT INTO Total_survey
SET P01 = '".floatval($row['total_P01'])."',
P02 = '".floatval($row['total_P02'])."' ";
- or intval() if your results are integers.
Edit: For 3 tables:
SELECT SUM(t.P01) AS total_P01, SUM(t.P02) AS total_P02
FROM (SELECT P01, P02 FROM graduate_survey
UNION ALL
SELECT P01, P02 FROM Alumni_survey
UNION ALL
SELECT P01, P02 FROM faculty_survey) t
But I don't think it is a good idea. You have tables with the same structure holding similar data. A better approach would be to make just 1 more column in one table and write for each record is it for graduates, alumnies or faculties. Holding 3 separate tables for this job just makes your database structure hard to understand and hard to use. You can make these two tables:
Survey: id(pk), group_id(int), PO1, PO2
and a description table:
Groups: group_id(pk), group_name(varchar)
This way you can have unlimited number of survey groups, you can extend their number dynamically from your program and handle their data much easier.