我有两个包含一些特定数据的表:
users:
+----+------------+
| id | username |
+----+------------+
| 1 | rob |
| 2 | john |
| 3 | jane | <--- jane never has donated
+----+------------+
donations:
+--------------------+------------+
| uid | amount | date |
+---------+----------+------------+
| 1 | 20 | 2013-10-10 |
| 2 | 5 | 2013-10-03 |
| 2 | 50 | 2013-09-25 |
| 2 | 5 | 2013-10-01 |
+---------+----------+------------+
Result I want:
+---------+-------------+---------+-------------+
| id | username | amount | monthly | <- sum of donations this month
+---------+-------------+---------+-------------+
| 1 | rob | 20 | 1 |
| 2 | john | 60 | 3 |
| 3 | jane | 0 | 0 | <- jane added
+---------+-------------+-----------------------+
这是我的查询:
SELECT t1.*, sum(t2.amount) amount, count(*) as monthly
FROM users t1
inner join donations t2
on t2.uid = t1.id
group by t1.username
编辑:忘记添加简,他从未捐赠过。
我怎么能做到这一点?