简体   繁体   English

我如何才能从PHP mysql中的两个或多个表中求和字段值

[英]how i can SUM field values from two or more tables in php mysql

I have six tables with each has two columns named (meal, cost). 我有六个表,每个表都有两个名为(餐,成本)的列。 I can SUM meal of one table. 我可以合计一桌饭。 but I want to SUM the total meal of every table. 但是我想对每张桌子的总和求和。

but like this.i have six tables. 但是像这样。我有六个桌子。 and I want to SUM the cost of every table at a time. 我想一次汇总每张桌子的费用。

$qq="select SUM(cost5) as 'sumcost' from shawon"; 
$res=mysqli_query($conn,$qq); $data=mysqli_fetch_array($res);  
echo "<div class='container'>". "sum of cost: ".$data['sumcost']."</div>";

is there any way to do it? 有什么办法吗?

You can use union all for buil an unique table with the same column mean, cost form each of six tables 您可以使用union all来构建具有相同列均值的唯一表,成本形成六个表中的每个表

select meal, sum(cost)
from (
  select  meal,cost
  from table1 
  union all 
  select  meal,cost
  from table2
  union all 
  select  meal,cost
  from table3
  union all 
  select  meal,cost
  from table4
  union all 
  select  meal,cost
  from table5
  union all 
  select  meal,cost
  from table6
  ) t 
  group by  meal 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM