表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(),其con_projects status中的p_id为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_trsanction.amount的所有活动项目(con_trsaction.p_id = con_projects.id AND con_projects.status = 1)id(p_id)
最佳答案
尝试这个:
SELECT SUM(t.amount)
FROM con_transactions t
INNER JOIN con_projects AS p ON t.p_id = p.id
WHERE p.status = 1
这是一个简单的联接操作。汇总中仅考虑“活动”项目。
关于php - SQL SUM()全部带有来自其他表的检查,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35498770/