在Mysql中总结

时间:2012-10-14 15:54:30

标签: php mysql sum

我在同一个数据库中有来自不同表的3个不同查询

 $sum = "SELECT htno, SUM(tm) AS tech FROM table1 WHERE htno='$id'";

 $sum1 = "SELECT htno, SUM(em) AS tech1 FROM table2 WHERE htno='$id'";

 $sum2= "SELECT htno, SUM(hm) AS tech2 FROM table3 WHERE htno='$id'";

现在我想添加tech,tech1和tech2

2 个答案:

答案 0 :(得分:2)

这不容易吗?

SELECT htno, SUM(tm) + SUM(em) + SUM(hm),....

更新1

SELECT x.htno, SUM(x.tech)
FROM
    (
        SELECT htno, SUM(tm) AS tech FROM....WHERE...GROUP BY...
        UNION ALL
        SELECT htno, SUM(em) AS tech  FROM....WHERE...GROUP BY...
        UNION ALL
        SELECT htno, SUM(hm) AS tech  FROM....WHERE...GROUP BY...
    ) x
GROUP BY x.htno

答案 1 :(得分:0)

试试这个:

SELECT htno, 
       Sum(tm) + Sum(em) + Sum(hm) AS tech4 
FROM   table1 
       INNER JOIN table2 
              ON table1.htno = table2.htno 
       INNER JOIN table3 
              ON table3.htno = table2.htno 
GROUP  BY table1.htno