PHP代码列出所有具有总值的用户从其他表中收集

时间:2014-08-28 03:36:40

标签: php mysql

表A

-----------------
a_id | user _a  | 
-----------------
1        |adam  |
2        |jose     |
3        |adam  |
4        |adam  |
5        |anne   |
6        |jose     |

表B

--------------------------------------
b_id | user_b   | value1 | value2 
--------------------------------------
1        |adam  | 33          | 9
2        |jose     | 46          |88
3        |adam  | 77          |21
4        |adam  | 81          |15
5        |anne   | 11          |67
6        |jose     | 45          |6

表C

--------------------------------------
c_id | user_c  | value1 | value2 
--------------------------------------
1        |adam  | 33          | 9
2        |jose     | 46          |88
3        |adam  | 77          |21
4        |adam  | 81          |15

表D

--------------------------------------
d_id | user_d   | value1 | value2 
--------------------------------------
1        |adam  | 33          | 9
2        |jose     | 46          |88

如何查看value1和value2的总值。 示例:我希望我的列表视图页面看起来像这样。

--------------------------------------------------------
user  | total value of value1 | total value of value2
---------------------------------------------------------
adam  |415                    | 99
jose    |183                     | 270
anne  |11                       | 67

请。帮助

1 个答案:

答案 0 :(得分:1)

这是一种使用SQL查询获取指定结果的方法(独立于PHP中的任何处理):

SELECT t.user_t      AS `user`
     , SUM(t.value1) AS `total value of value1`
     , SUM(t.value2) AS `total value of value2`
  FROM ( SELECT b.user_b      AS user_t
              , SUM(b.value1) AS value1
              , SUM(b.value2) AS value2
           FROM table_b b 
          GROUP BY b.user_b
          UNION ALL
         SELECT c.user_c      AS user_t
              , SUM(c.value1) AS value1
              , SUM(c.value2) AS value2
           FROM table_c c 
          GROUP BY c.user_c
          UNION ALL
         SELECT d.user_d      AS user_t
              , SUM(d.value1) AS value1
              , SUM(d.value2) AS value2
           FROM table_d d 
          GROUP BY d.user_d
       ) t
 GROUP BY t.user_t
 ORDER BY 2 DESC