Make sum of all table row field in PHP

2019-09-02 01:29发布

问题:

I have 4 tables, in this all tables have 3 rows[record] and 3 column[field] field like Date Name Total. This table like below:

First Table

   Date                  Name                      Total
 2012-11-07             Manoj                       10
 2012-11-08             Ganesh                       4
 2012-11-09             Sri                         30

Second Table

  Date                   Name                      Total
2012-11-07               Raju                         5
2012-11-08               ggg                          3
2012-11-09               Shshi                       30

Third Table

 Date                   Name                      Total
2012-11-07              Ram                         2
2012-11-08               gm                         5
2012-11-09             Shsse                       30

I need Output Like following type in PHP

Date          Total
2012-11-07      17
2012-11-08      12
2012-11-09      90

It should display all total in between date in PHP

回答1:

You can use a UNION ALL:

select date, sum(total) AllTotal
from
(
  select date, total
  from table1
  union all
  select date, total
  from table2
  union all
  select date, total
  from table3
) src
group by date

See SQL Fiddle with Demo

Or you might be able to use a LEFT JOIN similar to this:

select t1.date, sum(t1.total + t2.total + t3.total) AllTotal
from table1 t1
left join table2 t2
  on t1.date = t2.date
left join table3 t3
  on t1.date = t3.date
group by t1.date

See SQL Fiddle with Demo



回答2:

SELECT DATE, SUM(Total) totalSum
FROM
(
    SELECT * FROM tableA
    UNION ALL
    SELECT * FROM TableB
    UNION ALL 
    SELECT * FROM tableC
) s
GROUP BY DATE
  • SQLFiddle Demo


回答3:

select tbl1.date,sum(total)
from tbl1,
tbl2,
tbl3
where tbl1.date = tbl2.date and
tbl2.date = tbl3.date
group by tbl1.date;


标签: php mysql sum