SQL SUM()全部带有来自其他表的检查

时间:2016-02-19 06:32:40

标签: php mysql sql

表con_projects

mysql> SELECT * FROM con_projects;
+----+---------------+---------------------+--------+
| id | project_name  | project_description | status |
+----+---------------+---------------------+--------+
|  1 | Project 1     | Description IS Here |      1 |
|  2 | Project 2     | Description IS Here |      0 |
|  3 | Project 3     | Description IS Here |      1 |
|  4 | Project 4     | Description IS Here |      0 |
|  5 | Project 5     | Description IS Here |      1 |
+----+---------------+---------------------+--------+

此处状态1 =有效,0 =无效

mysql> SELECT * FROM con_transactions;
+------+------+---------------------+--------+
| t_id | p_id | date                | amount |
+------+------+---------------------+--------+
|   10 |    1 | 2016-02-17 19:24:05 | 1800   |
|   12 |    2 | 2016-02-18 11:40:13 | 200    |
|   17 |    3 | 2016-02-18 11:42:04 | 100    |
|   19 |    4 | 2016-02-18 11:45:43 | 1      |
|   20 |    5 | 2016-02-18 11:45:54 | 999    |
|   21 |    1 | 2016-02-18 11:46:02 | 1500   |
|   41 |    2 | 2016-02-18 17:23:14 | 500    |
|   42 |    3 | 2016-02-18 17:23:14 | 500    |
|   43 |    4 | 2016-02-18 17:23:15 | 500    |
|   44 |    5 | 2016-02-18 17:23:16 | 500    |
|   45 |    1 | 2016-02-18 17:23:16 | 500    |
|   46 |    2 | 2016-02-18 17:23:16 | 500    |
|   47 |    3 | 2016-02-18 17:23:17 | 500    |
|   48 |    4 | 2016-02-18 17:23:17 | 500    |
|   49 |    5 | 2016-02-18 17:23:18 | 500    |
|   50 |    1 | 2016-02-18 17:25:54 | 1000   |
|   51 |    1 | 2016-02-18 17:26:22 | 3000   |
|   52 |    2 | 2016-02-18 17:48:59 | 10     |
|   53 |    1 | 2016-02-18 17:48:59 | 10     |
|   55 |    1 | 2016-02-19 10:20:12 | 1000   |
+------+------+---------------------+--------+

现在我想从con_trnsactions获取SUM()所有金额,其中p_id来自con_projects status = 1

我尝试了这个以及更多

mysql> SELECT (SELECT SUM(t.amount) FROM con_transactions t WHERE p.id=t.p_id) as total FROM con_projects p WHERE status='1'
+-------+
| total |
+-------+
| 14120 |
+-------+

mysql> SELECT SUM(amount) from con_transactions;
+-------------+
| SUM(amount) |
+-------------+
|       14120 |
+-------------+

两者都是一样的。但减法将是这样的。

mysql> SELECT 1800+100+999+1500+500+500+500+500+500+1000+3000+10+1000;
+---------------------------------------------------------+
| 1800+100+999+1500+500+500+500+500+500+1000+3000+10+1000 |
+---------------------------------------------------------+
|                                                   11909 |
+---------------------------------------------------------+

这里是所有活动项目(con_trsaction.p_id = con_projects.id AND con_projects.status = 1)id(p_id)来自con_trsanction.amount

2 个答案:

答案 0 :(得分:3)

试试这个:

SELECT SUM(t.amount) 
FROM con_transactions t 
INNER JOIN con_projects AS p ON t.p_id = p.id
WHERE p.status = 1

这是一个简单的连接操作。只有'活跃'项目将在总和中计算。

答案 1 :(得分:2)

SELECT SUM(amount) from con_transactions LEFT JOIN con_projects ON con_projects.id = con_transactions.p_id WHERE con_projects.status = 1;