SQL SUM()不同的表不同的列

时间:2016-02-17 14:40:16

标签: php mysql sql database pdo

类别表

mysql> SELECT * FROM cats;
+------+-----------+
| c_id | c_name    |
+------+-----------+
|    1 | cats 1    |
|    2 | cats 2    |
|    3 | cats 3    |
+------+-----------+

元表

mysql> SELECT * FROM meta;
+------+------+----------+-------------+-------+
| m_id | c_id | name     | description | costs |
+------+------+----------+-------------+-------+
|    1 |    1 | Abhijit1 | description | 100   |
|    2 |    1 | Abhijit2 | description | 200   |
|    3 |    2 | Abhijit3 | description | 500   |
|    4 |    3 | Abhijit4 | description | 800   |
+------+------+----------+-------------+-------+
元和猫表常见的是c_id 元表猫c_id(1)元表有2个(Abhijit1,Abhijit2)行与m_id(1,2)

交易表

mysql> SELECT * FROM transactions;
+------+------+------------+--------+
| t_id | m_id | date       | amount |
+------+------+------------+--------+
|    1 |    1 | 2016-02-01 | 50     |
|    2 |    1 | 2016-02-06 | 50     |
|    3 |    3 | 2016-02-15 | 400    |
|    4 |    4 | 2016-02-19 | 150    |
+------+------+------------+--------+

事务和元表常见的是m_id m_id 1的事务有2行t_id(1,2) 该表主要用于支付金额和日期

我想对每个类别的所有成本(来自元表)和金额(来自交易表)求和()。

表与

连接
cats.c_id
    |
    |-----> meta.c_id
    |-----> meta.m_id
                |-----> transactions.m_id

这是错的。猫id 1的成本是300,但在这里我得到400

I Want Get Return From Query Like This:
+------+-----------+--------------+---------------+
| c_id | c_name    | SUM(m.costs) | SUM(t.amount) |
+------+-----------+--------------+---------------+
|    1 | cats 1    |          300 |           100 |
|    2 | cats 2    |          500 |           400 |
|    3 | cats 3    |          800 |           150 |
+------+-----------+--------------+---------------+

此处SUM(m.costs)均为类别的成本,SUM(t.amount)均为类别支付

请帮助我或任何更好的表管理理念。

2 个答案:

答案 0 :(得分:3)

问题来自于您加入transactions以获得SUM(t.amount)这一事实。因此,如果单个costs记录与两个meta记录相关联,transactions值会被计算两次。

您可以使用相关子查询来计算SUM(t.amount)

来解决此问题
SELECT c.c_id, 
       c.c_name, 
       SUM(m.costs),
       (SELECT SUM(t.amount)
        FROM transactions AS t
        WHERE m.m_id = t.m_id)
FROM cats AS c
LEFT JOIN meta AS m ON c.c_id = m.c_id
GROUP BY c.c_id, c.c_name

<强>输出:

c_id c_name  SUM(m.costs)   SUM(t.amount) 
-----------------------------------------
1    cats 1  300            100
2    cats 2  500            400
3    cats 3  800            150

Demo here

答案 1 :(得分:0)

试试这个

SELECT cats.c_id,
       cats.c_name,
       (SELECT SUM(m.cost) FROM meta WHERE cats.c_id = m.c_id) AS cost,
      (SELECT SUM(t.cost) FROM meta WHERE t.id = m.id) AS amount
WHERE c.c_id = 1