使用count和sum从多个表中收集数据

时间:2015-03-17 04:41:46

标签: php mysql sql

SELECT sum(amount) as amount , COUNT(userid) as total FROM table1 WHERE userid='1111'  union all 
SELECT sum(amount) as amount,  COUNT(userid) as total FROM table2 WHERE userid='1111' union all 
SELECT sum(amount) as amount,  COUNT(userid) as total FROM table3 WHERE userid='1111' union all 
SELECT sum(amount) as amount,  COUNT(userid) as total FROM table4 WHERE userid='1111' union all 
SELECT sum(amount) as amount,  COUNT(userid) as total FROM table5 WHERE userid='1111'

我在某个地方找到了它,但它不适合我。

建议的解决方案:

另一个选项是分别从所有表中获取数据,然后显示它。

问题:

我想通过单个查询从多个表中获取数据。将添加金额,并将从所有表格中计算用户ID。

附加说明: 它应该收集有关用户id = 1111的所有信息并保存在两个varibable中。

Userid = 1111,某些表格中可能不存在。

期待将是这样的:

你的总数:$ total |和你的金额:$ amount

基于建议。这是我到目前为止已经实现的,以及我如何展示它。它没有显示任何错误: 如果我使用单个查询,则结果显示正常。

<?php
$sqltotal=mysql_query("SELECT SUM(data.Amount) as Amount ,SUM(data.total) as total 
FROM
   (
     SELECT COALESCE(sum(amount),0) as amount , COALESCE(COUNT(userid)) as total FROM table1  WHERE userid='1111' 
     UNION ALL
     SELECT COALESCE(sum(amount),0) as amount,  COALESCE(COUNT(userid)) as total FROM table2 WHERE userid='1111'
     UNION ALL
     SELECT COALESCE(sum(amount),0) as amount,  COALESCE(COUNT(userid)) as total FROM table3 WHERE userid='1111'
     UNION ALL
     SELECT COALESCE(sum(amount),0) as amount,  COALESCE(COUNT(userid)) as total FROM table4 WHERE userid='1111'
     UNION ALL  
     SELECT COALESCE(sum(amount),0) as amount,  COALESCE(COUNT(userid)) as total FROM table5  WHERE userid='1111'
  ) as data
");
while($row = mysql_fetch_array($sqltotal))  
{
echo "$row[total]";
echo "$row[sum]";
}

//echo "$yourtotal: $row[total]";

?>

3 个答案:

答案 0 :(得分:0)

SELECT sum(amount) as amount , COUNT(userid) as total FROM table1
Group By userid

答案 1 :(得分:0)

如果您需要列amount的所有表总和的单行,那么只需在UNION上进行外部选择。现在正如您在评论中提到的那样,某些表可能不包含UserID,您需要使用COALESCE来确保null 0然后选择SELECT SUM(COALESCE(data.Amount,0)) as Amount ,SUM(COALESCE(data.total,0)) as total FROM ( SELECT COALESCE(sum(amount),0) as amount , COALESCE(COUNT(userid)) as total FROM table1 WHERE userid='1111' UNION ALL SELECT COALESCE(sum(amount),0) as amount, COALESCE(COUNT(userid)) as total FROM table2 WHERE userid='1111' UNION ALL SELECT COALESCE(sum(amount),0) as amount, COALESCE(COUNT(userid)) as total FROM table3 WHERE userid='1111' UNION ALL SELECT COALESCE(sum(amount),0) as amount, COALESCE(COUNT(userid)) as total FROM table4 WHERE userid='1111' UNION ALL SELECT COALESCE(sum(amount),0) as amount, COALESCE(COUNT(userid)) as total FROM table5 WHERE userid='1111' ) as data 值。

LEFT JOIN

如果您想使用加入,则需要使用SUM并且还需要为每个表单独执行{{1}},然后将其添加到主要总计中。

答案 2 :(得分:0)

试试这个:

SELECT sum(table1.amount + table2.amount + table3.amount + table4.amount) as amount, COUNT(table1.userid) + COUNT(table2.userid) + COUNT(table3.userid) + COUNT(table4.userid) as total
FROM table1, table2, table3, table4
WHERE table1.userid='1111' OR table2.userid='1111' OR table3.userid='1111' OR table4.userid='1111'